Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain multiple functions?

Tags:

clojure

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)
like image 837
yegor256 Avatar asked May 27 '13 12:05

yegor256


People also ask

How do you chain multiple functions in Python?

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.


3 Answers

Use -> macro.

(-> foo f1 f2 f3 f4)

Or reduce:

(reduce #(%2 %1) foo [f1 f2 f3 f4])
like image 143
Ankur Avatar answered Sep 27 '22 19:09

Ankur


There is a threading macro ->:

(-> foo f1 f2 f3 f4)
like image 42
Alex B Avatar answered Sep 27 '22 19:09

Alex B


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))
like image 44
Michiel Borkent Avatar answered Sep 27 '22 19:09

Michiel Borkent