/ Published in: Clojure
Using keyword arguments in Clojure functions.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
=>(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))
URL: http://stuartsierra.com/2010/01/15/keyword-arguments-in-clojure