Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flip order of passed arguments

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]
like image 981
Anton Harald Avatar asked Feb 21 '16 19:02

Anton Harald


3 Answers

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))))
like image 179
Chris Murphy Avatar answered Nov 05 '22 20:11

Chris Murphy


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.

like image 5
johnbakers Avatar answered Nov 05 '22 20:11

johnbakers


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"]
like image 4
daShader Avatar answered Nov 05 '22 20:11

daShader