什么时候使用如果与在Clojure中 [英] When to use if vs. when in Clojure

查看:114
本文介绍了什么时候使用如果与在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?

推荐答案

code> if 当你有一个真值和一个假的情况,你不需要一个隐式的 do 块。相反,当你只需要处理真实情况和隐式 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))


$ b b

if 情况下,只有 do-something 才会运行 my -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.

这篇关于什么时候使用如果与在Clojure中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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