In clojure, I would like to push a thrush value through a list of functions, but I’m not sure how to do so in an idiomatic way. The idea is that I will have a list containing an unknown number of functions, and I’d like to take advantage of the variadic nature of thrush.
So, something like this…
(->> 1 inc inc inc)
; 4
(->> 1 '(inc inc inc))
; does not work, of course
I think
compis the most idiomatic option here, though it will have prefix syntax instead. This is also more in keeping with normal Clojure (fn args) notation.Combine it with the idiomatic
applyif a function normally takes variadic arguments, but you want to feed it a collection.Be aware though it threads from right to left
This also complies more with Clojure/Lisp s-expressions.
If you want more ‘easy’ human readable notation, Arthur Ulfeldt’s answer is perfecly acceptable, and a nice example of reduce and functional programming. Using it ‘as is’ might get in the way of getting acquainted with the ‘simplicity’ of s-expressions though..
Be careful with macro’s !
The reason why -> and ->> are macro’s is that they actively rewrite forms, so you can use normally incomplete argument notation like
(filter odd?)in their scope without having to resort to overuse ofpartial. This can’t be done with normal function compostition.Best learn to make the most of normal function composition before turning to macro’s. There’s a lot of pitfalls in them for the unaccustomed, and should be used sparingly.