A clj snippet #5

Today's post concerns nothing fancy, but rather touches upon some basic feature of Clojure which I didn't know about until recently. Common Lisp has this nice way of specifying keyword parameters.

(defun foo (x &key y z)
   (list x y z))
0.0s
FOO
(foo 1 :y 2)
0.0s
(1 2 NIL)
(foo 1 :z 2 :y 3)
0.0s
(1 3 2)

I thought Clojure doesn't support keyword parameters, but it actually does. There is a map destructuring syntax for rest arguments.

(defn foo [x & {:keys [y z]}]
  (list x y z))
0.1s
Clojure
user/foo
(foo 1 :y 2)
0.1s
Clojure
List(3) (1, 2, nil)
(foo 1 :z 2 :y 3)
0.1s
Clojure
List(3) (1, 3, 2)

This works because map destructuring also works with sequences.

Stay safe.

Runtimes (2)
Runtime Languages (1)