[ACCEPTED]-When to use let vs. if-let in Clojure-clojure

Accepted answer
Score: 82

I guess if-let should be used when you'd like 9 to reference an if condition's value in the 8 "then" part of the code:

i.e. instead 7 of

(let [result :foo]
  (if result
    (do-something-with result)
    (do-something-else)))

you write:

(if-let [result :foo]
  (do-something-with result)
  (do-something-else))

which is a little neater, and 6 saves you indenting a further level. As 5 far as efficiency goes, you can see that 4 the macro expansion doesn't add much overhead:

(clojure.core/let [temp__4804__auto__ :foo]
  (if temp__4804__auto__
    (clojure.core/let [result temp__4804__auto__]
      (do-something-with result))
    (do-something-else)))

This 3 also illustrates that the binding can't 2 be referred to in the "else" part 1 of the code.

Score: 35

A good use case for if-let is to remove the need 8 to use anaphora. For example, the Arc programming 7 language provides a macro called aif that allows 6 you to bind a special variable named it within 5 the body of an if form when a given expression 4 evaluates to logical true. We can create 3 the same thing in Clojure:

(defmacro aif [expr & body]
  `(let [~'it ~expr] (if ~'it (do ~@body))))

(aif 42 (println it))
; 42

This is fine and 2 good, except that anaphora do not nest, but 1 if-let does:

(aif 42 (aif 38 [it it]))
;=> [38 38]

(aif 42 [it (aif 38 it)])
;=> [42 38]

(if-let [x 42] (if-let [y 38] [x y]))
;=> [42 38]

More Related questions