Home > Net >  haskell Pattern Matching: implementing && operator
haskell Pattern Matching: implementing && operator

Time:10-27

I've seen on my Tutorial that the && operator could be defined as such:

True && True = True
_ && _ = False

But that the actual implementation on GHC is:

True && b = b
_ && _ = False

I understand the implementation, but I'm not clear if the first expression doesn't care about the order of the arguments; is that the case?

Because when i try implementing Logical Or in a similar way, i feel it behaves differently:

True || b = True
_ || _ = False

when i run it:

False || True

returns False

The correct implementation is actually:

False || b = b
_ || _ = True

But i feel the previous one should also function correctly...

CodePudding user response:

I'm not clear if the first expression doesn't care about the order of the arguments; is that the case?

The order of operands matters. The pattern True && b will match if and only if the left operand is True. It does not matter whether the right operand is True.

Because when i try implementing Logical Or in a similar way, i feel it behaves differently:

True || b = True
_ || _ = False

This definition will return True if and only if the left operand is True. Otherwise it will return False. This is not a correct implementation of || because || should return True regardless of which operand is True.

  • Related