flip order of passed arguments

我只是一个虾纸丫 提交于 2020-01-22 18:58:08

问题


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]

回答1:


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.




回答2:


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))))



回答3:


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"]


来源:https://stackoverflow.com/questions/35541142/flip-order-of-passed-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!