when-let

clojure.core

  • (when-let bindings & body)
bindings => binding-form test

When test is true, evaluates body with binding-form bound to the value of test

2 Examples top

  • ;; 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
    
  • ;; See examples for "if" explaining Clojure's idea of logical true
    ;; and logical false.
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:1685 top

(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)))))
Vars in clojure.core/when-let:
Used in 0 other vars

Comments top

2 comment(s) for when-let.

The word "bindings" seems not to be correct here. In fact when-let only accepts one binding and not multiple ones. So "bindings" might be confusing, at least it was for me.

Agreed. It ought to be "binding" for clarity.

Log in to add a comment.