You're viewing version 1.2.0 of when-let. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

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:1422 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: = count defmacro let vector? apply concat list seq vector when

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...).

Log in to add a comment.