0
votes

Let's say I have a set of functions that take no arguments, e.g.

(defn f1 [] 1)
(defn f2 [] 2)
(defn f3 [] 3)

I then make a list out of these functions: (list f1 f2 f3)

But how do I run the function returned by something like (first (list f1 f2 f3))?

In Common Lisp I might use funcall since f1 takes no arguments. In Clojure I've tried (apply (first (list f1 f2 f3)) ()), i.e. apply to an empty argument list, and this works, I indeed get 1.

But is there a better way to do this? i.e. is there a funcall equivalent in Clojure? (Is that even the right question to ask?)

1
indeed! thank you! - aurbital

1 Answers

2
votes

As the comment has pointed out, in Clojure all you need is to place the function object as the first (& possibly only) item in a list, written with parentheses.

For clarity, I often prefer to assign the function object to a variable, so it is more obvious what is occurring and counting multiple nesting levels of parens is not so critical. For example, I would write:

  (let [fns   [f1 f2 f3]
        f1    (first fns)]

and then we get

(f1) => 1

where you can choose any descriptive name in place of f1.