Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically evaluate a list of functions in Clojure

Tags:

clojure

I am trying figure out how to programmatically evaluate a list of functions.

Lets say that I have this code:

(defn foo
  []
  (println "foo"))

(defn bar
  []
  (println "bar"))

(def funcs [foo bar] )

I want execute all functions of funcs in a programmatically way.

I am tried use eval, but no succcess.

Thanks for any help.

like image 299
Édipo Féderle Avatar asked Jun 02 '26 18:06

Édipo Féderle


2 Answers

Use for if you want the return values, and are OK with lazy evaluation (your functions are not guaranteed to be called until you access the return value), and doseq if you don't need the values and are doing this for immediate side effects.

(doseq [f [foo bar]]
  (f))

(def fs
  (for [f [foo bar]]
    (f)))
like image 106
noisesmith Avatar answered Jun 05 '26 13:06

noisesmith


You can use juxt:

((apply juxt funcs))
like image 45
bsvingen Avatar answered Jun 05 '26 14:06

bsvingen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!