Is there a idiomatic / built-in way to flip the argument order that is passed to a function in Clojure?
As I do here with the definition of a helper function:
(defn flip [f & xs]
(apply f (reverse xs)))
(vector 1 2) ; [1 2]
(flip vector 1 2) ; [2 1]
I think it makes sense most times to create a flipped function that you use later, so the variation on your function would be this:
(defn flip [f]
(fn [& xs]
(apply f (reverse xs))))
A flip function does exist in other functional languages, but it's easy enough to do in Clojure as well, and you've already done it!
There are other ways to do it as well.
And here is a discussion about it from the Clojure mailing list.
You can also use anonymous inline function to re-define the order of arguments.
(vector "a" "b") ; ["a" "b"]
(#(vector %2 %1) "a" "b") ; ["b" "a"]
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