Search code examples
haskelltruthtable

How to define exclusive disjunction with Guards Using Haskell


this code is to define the exclusive disjunction truth table in haskell

Click here for more info on exclusive disjunction, XOR Code:

-- truth table concept of logical XOR
exclusiveDisjunction :: Bool -> Bool -> Bool
exclusiveDisjunction = x y
    |True True <- False
    |True False <- True 
    |False True <- True 
    |False False <- False
    |otherwise = x y

Results:

 Ex6^.hs:31:5:
        parse error on input ‘|’
    Failed, modules loaded: none.

how to set guards with two boolean values given the xor truth table in haskell syntax ?

Thank you Please specify your answer without using haskell built in operators, meaning do not use && ||.

why can't this just be done?

exclusiveDisjunction2 :: Bool -> Bool -> Bool
exclusiveDisjunction2 x y
    |True True = False
    |True False = True 
    |False True = True 
    |False False = False

this is the result after running

   Couldn't match expected type ‘Bool -> Bool’ with actual type ‘Bool’
    The function ‘False’ is applied to one argument,
    but its type ‘Bool’ has none
    In the expression: False False
    In a stmt of a pattern guard for
                   an equation for ‘exclusiveDisjunction2’:
      False False

Solution

  • You are making syntax errors. If you really want to use guards, you can do something like this:

    exclusiveDisjunction :: Bool -> Bool -> Bool
    exclusiveDisjunction x y 
        | x == True && y == True = False
        | x == True && y == False = True 
        | x == False && y == True = True
        | x == False && y == False = False
    

    But this can be more simply achieved by case expressions:

    exclusiveDisjunction :: Bool -> Bool -> Bool
    exclusiveDisjunction x y = case (x,y) of
                                 (True, True) -> False
                                 (True, False) -> True
                                 (False, True) -> True
                                 (False, False) -> False
    

    Or even more simply using the inbuilt disjunction operator:

    exclusiveDisjunction :: Bool -> Bool -> Bool
    exclusiveDisjunction x y = case (x,y) of
                                 (True, True) -> False
                                 otherwise -> x || y