The Clojure (or Lisp) Equivalent of a Compound Boolean Test

后端 未结 4 1549
暗喜
暗喜 2021-02-05 06:25

In C++ I\'d write something like this:

if (a == something && b == anotherthing)
{
   foo();
}

Am I correct in thinking the Clojure equi

4条回答
  •  无人及你
    2021-02-05 07:08

    In Common Lisp, the following is also a common idiom:

    (when (and (= a something) (= b another))
      (foo))
    

    Compare this to Doug Currie's answer using (and ... (foo)). The semantics are the same, but depending on the return type of (foo), most Common Lisp programmers would prefer one over the other:

    • Use (and ... (foo)) in cases where (foo) returns a boolean.

    • Use (when (and ...) (foo)) in cases where (foo) returns an arbitrary result.

    An exception that proves the rule is code where the programmer knows both idioms, but intentionally writes (and ... (foo)) anyway. :-)

提交回复
热议问题