views:

717

answers:

4

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

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

Am I correct in thinking the Clojure equivalent is something like this:

(if (= a something)
    (if (= b anotherthing)
        (foo)))

Or is there another way to perform a logical "and" that I've missed? As I said the latter form seems to work correctly--I was just wondering if there's some simpler way to perform the logical and. And searching for "boolean" "logical" and "and" on the Clojure Google Group turned up too many results to be much use.

+23  A: 

In Common Lisp and Scheme

(and (= a something) (= b another) (foo))
Doug Currie
Short and sweet.
Allain Lalonde
Ah, short circuiting is so nice, isn't it?
Cristián Romo
Thanks Doug. I don't know why it never occurred to me to check for "and" on the Clojure website. Seems so bloody obvious now.
Onorio Catenacci
You can also check from within clojure, e.g. `(doc and)`.
Brian Carper
+15  A: 

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. :-)

David Lichteblau
Thank you. I'm learning clojure and that's very helpful.
Onorio Catenacci
+2  A: 

In Clojure I would normally use something like:

(if 
  (and (= a something) (= b anotherthing))
  (foo))

It is clearly possible to be more concise (e.g. Doug's answer) but I think this approach is more natural for people to read - especially if future readers of the code have a C++ or Java background!

mikera
+1  A: 

It's really cool! (and x y) is a macro -- you can check the source code at clojure.org -- that expands to (if x y false) equivalent to:

if (x) {
  if (y) {
    ...
  }
} else {
  false
}

(or x y) is similar but reversed.

Ralph