Return to Snippet

Revision: 22629
at January 17, 2010 10:14 by narkisr


Initial Code
=>(defn foo [{a :keyA, b :keyB}](list a b))
=>(foo {:keyA 1 :keyB 2})
(1 2)

; mixing with normal parameters
=>(defn foo [a b {c :keyC, d :keyD}](list a b c d))
=> (foo 1 2 {:keyC 3, :keyD 4})
(1 2 3 4)

; keys and variables have the same name (using :keys auto assigns them).
=>(defn foo [{:keys [a b]}] (list a b))
=>(foo {:a 5, :b 6})
(5 6)

; enforcing existence of a key using pre condition
=>(defn foo [{:keys [a b c]}] 
   {:pre [(not (nil? c))]}
    (list a b c))
=>(foo {:a 1, :c 3})
(1 nil 3)
=>(foo {:b 2})
java.lang.AssertionError: Assert failed: (not (nil? c))

Initial URL
http://stuartsierra.com/2010/01/15/keyword-arguments-in-clojure

Initial Description
Using keyword arguments in Clojure functions.

Initial Title
keyword arguments in clojure

Initial Tags


Initial Language
Clojure