5

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)
yegor256
  • 102,010
  • 123
  • 446
  • 597
  • see http://stackoverflow.com/questions/11918554/can-clojure-evaluate-a-chain-of-mixed-arity-functions-and-return-a-partial-funct and see if that helps you –  May 27 '13 at 12:26

3 Answers3

9

Use -> macro.

(-> foo f1 f2 f3 f4)

Or reduce:

(reduce #(%2 %1) foo [f1 f2 f3 f4])
Ankur
  • 33,367
  • 2
  • 46
  • 72
  • 3
    @vemv I think the `->` is cute. The `reduce` option clearly shows the operational pattern, and, unlike the threading macro, is happy to take on a sequence unknown at compile-time. – A. Webb May 27 '13 at 13:47
5

There is a threading macro ->:

(-> foo f1 f2 f3 f4)
Alex B
  • 82,554
  • 44
  • 203
  • 280
4

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))
Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149