keyword arguments in clojure


/ Published in: Clojure
Save to your folder(s)

Using keyword arguments in Clojure functions.


Copy this code and paste it in your HTML
  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))

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.