何时使用“if”和“何时”在Clojure? [英] When to use "if" and "when" in Clojure?

查看:142
本文介绍了何时使用“if”和“何时”在Clojure?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候比另一个好?
是一个比另一个更快还是唯一的区别是返回false或nil?

When is one better than the other? Is one faster than the other or does the only difference is the return of false or nil?

推荐答案

使用 if 当你只有一个truthy和一个假的情况而你不需要一个隐含的 do 块。相反,当你只需要处理真实案例和隐式时,应该使用。速度没有区别,这是使用最惯用的风格。

Use if when you have exactly one truthy and one falsy case and you don't need an implicit do block. In contrast, when should be used when you only have to handle the truthy case and the implicit do. There is no difference in speed, it's a matter of using the most idiomatic style.

 (if (my-predicate? my-data)
     (do-something my-data)
     (do-something-else my-data))

 (when (my-predicate? my-data)
     (do-something my-data)
     (do-something-additionally my-data))

if 的情况下,如果我只会运行 do-something -predicate?返回一个真实的结果,而在的情况下,两个 do-something do-something-additional 被执行。

In the if case, only do-something will be run if my-predicate? returns a truthy result, whereas in the when case, both do-something and do-something-additionally are executed.

这篇关于何时使用“if”和“何时”在Clojure?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆