I'm looking for a clean, idiomatic way to do a "backwards reduce" in Clojure.
I've got
(def fns '(fn1 fn2 fn3))
(def val 42)
I'd like to obtain (fn3 (fn2 (fn1 val)))
, and I'm not picky about the order. So I'd like to consecutively apply a sequence of functions to a value, rather than consecutively a sequence of values to a function.
Suggestions? Thanks!
This is just reduce. Remember functions are objects too. Also, you are still applying your functions in order f1, then f2, etc. Don't be confused with the fact that it reads (f4 (f3 ...
So just use a regular reduce.
(reduce #(%2 %1) val functions)
Yet another way to think about it is as a composition of functions:
user=> ((apply comp [inc dec inc]) 42)
43
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