7

I have a function called show which shows a dialog with the message. I need to map this function to all the items in alist. But Clojure doesnt show me any messages. What am I doing wrong?

(defn show[message]
 (. javax.swing.JOptionPane (showMessageDialog nil message)))

(defn action[]
    (map show '(HELLO Sweet love)))

2 Answers 2

7

map is lazy. Nothing is going to be evaluated until you force it to be evaluated. Either (dorun (action)) or use doseq instead of map.

Sign up to request clarification or add additional context in comments.

Comments

5

the map function doesnt actually run the mapped function on each memeber of the collection. rather it returns a 'lazy-cons' cell. this looks a lot like your classic singly linked list with one very important difference, the data in each cell is computed at the time that it is read not the time it is defined (this result is of course stored for later reads). So in order to have the function actually run you have to read the result of running the function. Because in this case you dont care about the result of the function only that it ran clojure provides a great wrapper function called

(dorun .... insert your map here .... )

that will create the map, read the results and promptly throw them out with out wasting memory storing them for later.

If you where mapping a function with results you wanted to keep then use doseq instead.

2 Comments

Thanks for the detailed answer. Are all the list abstractions lazy? How do I know which ones are and which ones are not?
i believe they all are except reverse, though vectors have an (rsec [1 2 3]) function that creates a sec starting at the end which usually solves that problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.