Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesnt Clojure execute this function at all?

Tags:

clojure

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)))
like image 314
unj2 Avatar asked Jul 23 '09 17:07

unj2


2 Answers

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.

like image 71
Brian Carper Avatar answered Nov 17 '22 21:11

Brian Carper


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.

like image 44
Arthur Ulfeldt Avatar answered Nov 17 '22 23:11

Arthur Ulfeldt