When to use let vs. if-let in Clojure
何时使用
我想当您想在代码的"
即代替
1 2 3 4 | (let [result :foo] (if result (do-something-with result) (do-something-else))) |
您写:
1 2 3 | (if-let [result :foo] (do-something-with result) (do-something-else)) |
有点整洁,可节省缩进一个层次。就效率而言,您可以看到宏扩展不会增加太多开销:
1 2 3 4 5 | (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))) |
这也说明了绑定不能在代码的"
1 2 3 4 5 | (defmacro aif [expr & body] `(let [~'it ~expr] (if ~'it (do ~@body)))) (aif 42 (println it)) ; 42 |
这很好,很好,除了回指不嵌套,而
1 2 3 4 5 6 7 8 | (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] |