Ono*_*cci 21 lisp boolean clojure
在C++中我会写这样的东西:
if (a == something && b == anotherthing)
{
foo();
}
Run Code Online (Sandbox Code Playgroud)
我认为Clojure等价物是这样的:
(if (= a something)
(if (= b anotherthing)
(foo)))
Run Code Online (Sandbox Code Playgroud)
或者是否有另一种方法来执行我错过的逻辑"和"?正如我所说,后一种形式似乎工作正常 - 我只是想知道是否有一些更简单的方法来执行逻辑和.在Clojure Google Group上搜索"boolean""logical"和"and"会产生太多结果,但却没有多大用处.
Dou*_*rie 35
在Common Lisp和Scheme中
(and (= a something) (= b another) (foo))
Run Code Online (Sandbox Code Playgroud)
Dav*_*lau 17
在Common Lisp中,以下也是一个常见的习语:
(when (and (= a something) (= b another))
(foo))
Run Code Online (Sandbox Code Playgroud)
将此与Doug Currie的答案相比较(and ... (foo)).语义是相同的,但根据返回类型(foo),大多数Common Lisp程序员更喜欢一个:
(and ... (foo))在(foo)返回布尔值的情况下使用.
使用(when (and ...) (foo))在情况下(foo)返回任意结果.
证明规则的例外是程序员知道这两个习语的代码,但(and ... (foo))无论如何都是有意写的.:-)
在Clojure中,我通常会使用以下内容:
(if
(and (= a something) (= b anotherthing))
(foo))
Run Code Online (Sandbox Code Playgroud)
显然可能更简洁(例如Doug的答案),但我认为这种方法对于人们来说更自然 - 尤其是如果未来的代码读者具有C++或Java背景!
| 归档时间: |
|
| 查看次数: |
4387 次 |
| 最近记录: |