Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce a set of functions over a value?

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!

like image 843
Dan Avatar asked Dec 03 '22 07:12

Dan


2 Answers

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) 
like image 146
Mark Bolusmjak Avatar answered Dec 19 '22 00:12

Mark Bolusmjak


Yet another way to think about it is as a composition of functions:

user=> ((apply comp [inc dec inc]) 42)
43
like image 27
Timothy Pratley Avatar answered Dec 19 '22 01:12

Timothy Pratley