user2011931
user2011931

Reputation: 21

How to do this in clojure?

I need to do the following:

(defn make-menu [] (for [i (range 3)] '(+ i 100)))

I need make-menu to return: ('(+ 0 100) '(+ 1 100) '(+ 2 100))

Please note that the vector contains non-evaluated functions.

Is it possible to do this in Clojure?

Thank you for all your help!

Jakub

Upvotes: 2

Views: 101

Answers (1)

Michiel Borkent
Michiel Borkent

Reputation: 34790

(defn make-menu [] (for [i (range 3)] (list '+ i 100)))

or

(defn make-menu [] (for [i (range 3)] `(+ ~i 100)))

The first form is just a list of three elements: the symbol + quoted, i which evaluates to the value bound in the for list comprehension and 100.

The second form is an example of syntax-quote. Note the difference between normal quote ' and syntax-quote: the second allows evaluation of subforms, by prefixing ~. Also it fully qualifies symbols, so + becomes clojure.core/+. Normal quote simply quotes every subelement in the quoted form, so no evaluation is possible there.

Upvotes: 5

Related Questions