bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test
;; Very useful when working with sequences. Capturing the return value
;; of `seq` brings a performance gain in subsequent `first`/`rest`/`next`
;; calls. Also the block is guarded by `nil` punning.
(defn drop-one
[coll]
(when-let [s (seq coll)]
(rest s)))
user=> (drop-one [1 2 3])
(2 3)
user=> (drop-one [])
nil
(defmacro when-let
"bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test"
{:added "1.0"}
[bindings & body]
(assert-args when-let
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(when temp#
(let [~form temp#]
~@body)))))
Comments top
1 comment(s) for when-let.
The difference between when-let and if-let is that when-let doesn't have an else clause and and also accepts multiple forms so you don't need to use a (do...).