Created
January 22, 2012 03:32
-
-
Save alexpw/1655342 to your computer and use it in GitHub Desktop.
Clojure - Example using optional args through named keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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