Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

When to use let vs. if-let in Clojure

When does using if-let rather than let make code look better and does it have any performance impact?

question from:https://stackoverflow.com/questions/2010287/when-to-use-let-vs-if-let-in-clojure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

i.e. instead 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 saves you indenting a further level. As far as efficiency goes, you can see that 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 also illustrates that the binding can't be referred to in the "else" part of the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...