Skip to content

Instantly share code, notes, and snippets.

@micmarsh
Last active May 12, 2022 17:16
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micmarsh/bcbe19c9de8bb7a471bf to your computer and use it in GitHub Desktop.
Save micmarsh/bcbe19c9de8bb7a471bf to your computer and use it in GitHub Desktop.
Flip the arguments of a function, Clojure style
(defn flip [function]
(fn
([] (function))
([x] (function x))
([x y] (function y x))
([x y z] (function z y x))
([a b c d] (function d c b a))
([a b c d & rest]
(->> rest
(concat [a b c d])
reverse
(apply function)))))
; EXAMPLES
; ;one argument, doesn't change anything
; ((flip :foo) {:foo "bar"}) => "bar"
;
; ;two arguments, reverses order
; ((flip -) 1 2) => 1
;
; ;handles an arbitrary number of arguments
; (> 1 2 3 4 5) => false
; ((flip >) 1 2 3 4 5) => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment