Posted By

narkisr on 01/17/10


Tagged

map keyword arguments


Versions (?)

keyword arguments in clojure


 / Published in: Clojure
 

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

Using keyword arguments in Clojure functions.

  1. =>(defn foo [{a :keyA, b :keyB}](list a b))
  2. =>(foo {:keyA 1 :keyB 2})
  3. (1 2)
  4.  
  5. ; mixing with normal parameters
  6. =>(defn foo [a b {c :keyC, d :keyD}](list a b c d))
  7. => (foo 1 2 {:keyC 3, :keyD 4})
  8. (1 2 3 4)
  9.  
  10. ; keys and variables have the same name (using :keys auto assigns them).
  11. =>(defn foo [{:keys [a b]}] (list a b))
  12. =>(foo {:a 5, :b 6})
  13. (5 6)
  14.  
  15. ; enforcing existence of a key using pre condition
  16. =>(defn foo [{:keys [a b c]}]
  17. {:pre [(not (nil? c))]}
  18. (list a b c))
  19. =>(foo {:a 1, :c 3})
  20. (1 nil 3)
  21. =>(foo {:b 2})
  22. java.lang.AssertionError: Assert failed: (not (nil? c))

Report this snippet  

You need to login to post a comment.