Skip to content

Instantly share code, notes, and snippets.

@jamesmacaulay
Created February 20, 2013 05:09
Show Gist options
  • Save jamesmacaulay/4993062 to your computer and use it in GitHub Desktop.
Save jamesmacaulay/4993062 to your computer and use it in GitHub Desktop.
Like `if`, but operates on the level of functions.
(defmacro iffn
"Like `if`, but operates on the level of functions. Returns a function which applies its arguments to `test-fn`.
If the return value of `test-fn` is truthy, `then-fn` is called with the same arguments to get the return value.
Otherwise, `else-fn` is used. In other words, it lets you rewrite this:
#(if (pos? %) (inc %) (dec %))
as this:
(iffn pos? inc dec)"
[test-fn then-fn else-fn]
`(fn [& args#]
(if (apply ~test-fn args#)
(apply ~then-fn args#)
(apply ~else-fn args#))))
; some examples:
(let [magnify (iffn pos? inc dec)]
[(magnify -2)
(magnify 5)])
; [-3 6]
(let [toggle-membership (iffn contains? disj conj)]
[(toggle-membership #{:a :b} :a)
(toggle-membership #{:c :d} :z)])
; [#{:b} #{:z :c :d}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment