如何使用 Haskell 定义 Guards 的排他析取

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 代码:

-- 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

结果:

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

在 haskell 语法中给定 xor truth table 如何用两个布尔值设置守卫?

谢谢 请在不使用 haskell 内置运算符的情况下指定您的答案,这意味着不要使用 && ||。

为什么不能这样做?

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

这是运行

后的结果
   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

您犯了语法错误。如果你真的想使用守卫,你可以这样做:

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

但这可以通过 case 表达式更简单地实现:

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

或者更简单地使用内置的 disjunction 运算符:

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

如@sibi 所述,您犯了语法错误。但是你所做的是通过模式匹配实现的。

exclusiveDisjunction :: Bool -> Bool -> Bool
exclusiveDisjunction True True = False
exclusiveDisjunction True False = True 
exclusiveDisjunction False True = True 
exclusiveDisjunction False False = False

这可以简化为

exclusiveDisjunction :: Bool -> Bool -> Bool
exclusiveDisjunction True True = False
exclusiveDisjunction True False = True 
exclusiveDisjunction _ a = a

已经有很好的答案,但我想从我的角度展示如何以更清晰的方式实现它。

exclusiveDisjunction :: Bool -> Bool -> Bool
exclusiveDisjunction True = not
exclusiveDisjunction False = id

最短。

exclusiveDisjunction :: Bool -> Bool -> Bool
exclusiveDisjunction = (/=)