liveBook · Manning

When-let

As explained in Clojure: The Essential Reference

when-let is a Clojure macro that lexically binds a single value and evaluates a body of forms only when that value is truthy.

when-let is a Clojure macro for binding one value lexically and evaluating one or more body forms only when that value is logically true. It returns nil when the tested expression is false. section 3.1.2

Use the following contract:

  • Write one binding pair, [bind expr]; bind may use destructuring. section 3.1.2
  • Evaluate expr, bind its result, and expose that name to the body. section 3.1.2
  • Provide multiple body forms when needed; when-let wraps them in an implicit do. section 3.1.2
  • Choose if-let when an explicit alternative is required, or when-some when false should count as present. section 3.1.2

Guarding a resource lookup

(defn loc [resource] (when-let [f (io/resource resource)] (count (s/split-lines (slurp f))))) (loc "non-existent") ;; nil (total-loc "non-existent" "clojure/core.clj" "clojure/pprint.clj") ;; 7570 The bound resource is used only when lookup succeeds; missing resources contribute nil, which keep removes. section 3.1.2

Listing 3.3. → Local Binding, Lexical Scope, Conditional Assignment
(defmacro if-let
  ([bindings then])
  ([bindings then else))

(defmacro when-let
  [bindings & body])

(defmacro if-some
  ([bindings then])
  ([bindings then else))

(defmacro when-some
  [bindings & body])

Inspect the compact macro signatures for conditional binding and lexical scope. section 3.1.2

How Clojure: The Essential Reference covers it

How deep it goes
Defines the binding contract, truth behavior, implicit do semantics, return value, and related macro distinctions.
Examples
Uses resource lookup, line counting, aggregation with keep, and contrasts false-testing with nil-testing.
What it assumes
Assumes familiarity with Clojure forms, lexical bindings, evaluable expressions, and truthiness.
What you can do after
Apply it to conditionally process a bound value while returning nil when that value is logically false.
How it connects
Connects lexical binding with let, destructuring, if-let, if-some, and when-some.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.