Skip to content

Instantly share code, notes, and snippets.

@alexpw
Created January 22, 2012 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpw/1655342 to your computer and use it in GitHub Desktop.
Save alexpw/1655342 to your computer and use it in GitHub Desktop.
Clojure - Example using optional args through named keys
(defn my-math
"Example using optional args through named keys."
[nums & {:keys [operation]
:or {operation +}}]
(apply operation nums))
user=> (my-math '(1 2 3))
6
user=> (my-math '(1 2 3) :operation *)
6
user=> (my-math '(1 2 3) :operation /)
1/6
user=> (my-math '(1 2 3) :operation -)
-4
; Another approach using a nil argument and some clumsy validation.
(defn my-math2
"Example using optional args through named keys."
[nums & {:keys [operation]
:or {operation nil}}]
(let [op-fn (if (nil? operation) + operation)]
(apply op-fn nums)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment