Java 的 switch 在 Clojure 中等效吗?
Clojure 中是否有与 Java 的 switch
结构等效的东西?如果是,那是什么?如果不是,我们是否必须使用 if
else
梯子来实现?
Is there an equivalent for Java's switch
construct in Clojure? If yes, what is it? If no, do we have to use if
else
ladder to achieve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
case 是一个不错的选择,正如 Jan
cond 在许多相关情况下也非常有用,特别是如果您想在评估一系列不同条件表达式的基础上进行切换,例如
注意 cond 的结果是由第一个匹配的表达式决定的,所以负余额会显示“Overdrawn!”即使它也匹配低余额情况。
[我已经编辑了代码 - 删除了末尾的额外括号以使其正常工作]
case is a good option as pointed out by Jan
cond is also very useful in many related circumstances, particularly if you want to switch on the basis of evaluating a range of different conditional expressions, e.g.
Note that the result of cond is determined by the first matching expression, so a negative balance will display "Overdrawn!" even though it also matches the low balance case.
[I have edited the code - removed the extra bracket at the end to make it work]
尝试使用
case
宏:或使用默认值
请记住,根据文档
请参阅 ClojureDocs 查看更多示例。
Try the
case
macro:or with default value
Remember that according to the documentation
See more examples at ClojureDocs.
虽然 @Jan 和 @mikera 建议使用
大小写
或cond
(我可以添加condp
到列表中?)从功能性角度来看是合理的,尽管case
的限制(例如,测试值只能是编译时常量;默认返回值是强制的),与switch
的限制相同,但存在一些细微的差别:case
不能与 JavaEnum
常量一起使用;case
的调度基于哈希 AFAIK,这使得它在性能方面可与哈希图相媲美;switch
速度更快;你不能使用
case
,这意味着你必须使用其他选项(带有值集的condp
?)来镜像switch
的行为。[1] 不像功能编程<那样起作用/a>,功能性的,如履行一项功能、服务于一个目的。
Though @Jan and @mikera suggestions to use
case
orcond
(may I addcondp
to the list?) are sound from a functional¹ standpoint and thoughcase
's limitations (e.g. test values can only be compile-time constants ; a default return value is mandatory) mirror those ofswitch
there are some subtle differences:case
cannot be used with JavaEnum
constants ;case
's dispatch is based on hashing AFAIK which makes it comparable to hashmaps in terms of performance ;switch
is way faster ;you cannot fall-through with
case
, which means that you must use other options (condp
with value sets ?) to mirrorswitch
's behaviour.[¹] not functional as in functional-programming, functional as in fulfilling a function, serving a purpose.