I'm trying to chain a few functions in Clojure:
(f4 (f3 (f2 (f1 foo))))
Is there any convenient syntax sugar for this? Something like:
(with-all-of-them foo f1 f2 f3 f4)
If you want to define a function to be called multiple times, first you need to return a callable object each time (for example a function) otherwise you have to create your own object by defining a __call__ attribute, in order for it to be callable.
Use ->
macro.
(-> foo f1 f2 f3 f4)
Or reduce
:
(reduce #(%2 %1) foo [f1 f2 f3 f4])
There is a threading macro ->
:
(-> foo f1 f2 f3 f4)
Actually your description of with-all-of-them
is very close to comp
, except that comp
returns a function that you must call yourself:
(f4 (f3 (f2 (f1 foo))))
== ((comp f4 f3 f2 f1) foo)
So, with-all-of-them
could be implemented as follows:
(defn with-all-of-them [arg & fs]
((apply comp fs) arg))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With