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

查看:19
本文介绍了何时使用“如果"和“当"在 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?

推荐答案

当你只有一个真假案例并且不需要隐含的do时使用if代码>块.相反,当您只需要处理真实情况和隐式 do 时,应该使用 when.速度没有区别,就是用最地道的风格.

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 的情况下,如果 my-predicate? 返回一个真实的结果,只有 do-something 将被运行,而在 when 情况下,do-somethingdo-something-additionally 都会被执行.

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天全站免登陆