Vincenzo Maggio
Vincenzo Maggio

Reputation: 3869

Use list as Clojure function body

let's say that in Clojure I have a list defined like this:

(def function-body '(+ a b))

Next I would like to use the function-body list as the effective body of a function, so I would like to do something like:

(defn my-sum [a b] function-body)

to produce:

(defn my-sum [a b] (+ a b))

Which is valid Clojure code.

Is this possible in Clojure? If I should revert to macro, what kind of expansion should I use?

Upvotes: 1

Views: 146

Answers (3)

MasterMastic
MasterMastic

Reputation: 21286

(def function-body '(+ a b))
(eval `(defn ~'my-sum ~'[a b] ~function-body))

Quick explanation:

; what we eval above is this:
`(defn ~'my-sum ~'[a b] ~function-body)
; which becomes this:
; (clojure.core/defn my-sum [a b] (+ a b))
(my-sum 2 3) ; => 5

A macro would be very similar, i.e. just unquote the body.

Upvotes: 1

Thumbnail
Thumbnail

Reputation: 13473

I doubt that you need to keep the function body as a form. The function itself, (fn [a b] (+ a b)) in your example, is available as a thing you can pass as an argument, employ as an element in a data structure, as well as doing the function thing of calling upon arguments.

Your purpose is probably to have several functions available that you might call, according to circumstances. Keep them as functions, not as forms.

Upvotes: 2

RedDeckWins
RedDeckWins

Reputation: 2121

You would probably want to use a macro for this. The code as you have it would just return the list '(+ a b), not do any addition.

On another note what problem are you actually trying to solve? I don't really see why you would want to do something like this. You might be asking the wrong question.

Upvotes: 1

Related Questions