Tuesday 7 June 2016

Haskell: Implement Exclusive or operation

Exclusive or is a logical binary operation, it returns True, if any one of the operand is True, but not both.


Logical.hs
exOr :: Bool -> Bool -> Bool
exOr x y = (x || y) && not (x && y)

Prelude> :load Logical.hs 
[1 of 1] Compiling Main             ( Logical.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> let a = True
*Main> let b = True
*Main> let c = False
*Main> 
*Main> a `exOr` b
False
*Main> a `exOr` c
True


Following is another implementation of exOr function using pattern matching.


Sample.hs
exOr True x = not x
exOr False x = x

Previous                                                 Next                                                 Home

No comments:

Post a Comment