Arc Forumnew | comments | leaders | submitlogin
and operator
1 point by godtvisken 6139 days ago | 5 comments
I am having trouble understanding the and operator. Why do they not behave like i think they should?

arc> (and 0 0)

0

arc> (and 0 1)

1

arc> (and 1 0)

0

arc> (and 1 1)

1

I expected (and 0 1) to yield 0, not 1.



2 points by lojic 6139 days ago | link

0 and 1 are true in Arc, right? In other languages, if two operands to 'and' are true, 'and' returns the second. 'or' returns the first if true.

Try instead:

  (and nil nil)
  (and nil t)
  (and t t)

-----

2 points by godtvisken 6139 days ago | link

Ah.. I see. I forgot the way that "true" and "false" are represented in arc. Thank you.

-----

1 point by kennytilton 6139 days ago | link

and has to check them all and returns the last if all are non-nil. The OR operator would stop at the first non-nil (cuz then it's done) and return that.

-----

1 point by kennytilton 6139 days ago | link

I should add that you asked why it did not work as you expected, without explaining why you expected what you did so I am flailing here, but hey, it was it is. They could have returned the first of them or all of them or a boring t -- I think it was just a bit of hacker cleverness and a good guess (IMO) of what to use as a true return value.

-----

1 point by etfb 6139 days ago | link

It's basically saying: if any of my operands are nil, return nil; otherwise, return the final operand. So (and 1 2 3 4 5) should return 5, because none of those numbers is nil. But (and 1 2 nil 4 5) will return nil.

Incidentally, it only evaluates as far as it has to. (and (a) (b) (c)) will evaluate (a), then if the result is non-nil it will evaluate (b), then if the result of that is also non-nil it will evaluate (c) and return the answer to that last evaluation as the result of the whole expression.

This is different to a hypothetical bitwise and, which would evaluate at least until it reached zero, "and"ing the bits together as it goes. So (bitand 42 23), which is (bitand 101010 010111) in binary, would return 2, which is 000010 in binary. That's not what (and...) does.

-----