Haskell 不使用 == 或 /= 的与门

Haskell AND gate without using == or /=

不允许我使用 == 或 /=,但我不知道没有它们我该如何重写它。

iffC x y = 
if x == True && y == True then True
  else if x == False && y == False then True
    else False

iffG x y
  | y == True && x == True = True
  | y == False && x == False = True
  | otherwise = False

您可以像这样重写现有的解决方案,我认为这就是练习的目的。

iffC :: Bool -> Bool -> Bool
iffC x y = if x && y
           then True
           else False

iffG :: Bool -> Bool -> Bool
iffG x y | x && y = True
         | otherwise = False

iffP :: Bool -> Bool -> Bool
iffP True True = True
iffP _ _ = False

我真的不明白这个练习有什么指导意义,因为所有这些实现都是一种复杂的表达方式 &&

可以使用模式定义任何二元布尔运算符

op :: Bool -> Bool -> Bool
op x y =
   if x
   then if y then ... else ...
   else if y then ... else ...

其中四个 ... 基本上是 op 的真相 table。

通常这会导致像

这样的反模式
if z then True else False

应该改写为

z

if z then False else True

应该改写为

not z

if z then True else True

应该改写为

True

False 的类似情况。本质上,这样的 if 总是可以重写为 z, not z, True, False.

之一

模式匹配看起来很有用。

iffC :: Bool -> Bool -> Bool
iffC True True = True
iffC False False = True
iffC _ _ = False

你会得到让你的真相table可见的免费奖励。