代码之家  ›  专栏  ›  技术社区  ›  Daniel_H

Haskell和gate不使用==或/=

  •  0
  • Daniel_H  · 技术社区  · 6 年前

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

    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
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   chi    6 年前

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

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

    四个 ... 本质上是 op

    这通常会导致反模式,如

    if z then True else False
    

    应重写为

    z
    

    if z then False else True
    

    应重写为

    not z
    

    if z then True else True
    

    应重写为

    True
    

    或类似的情况 False 。本质上 if s始终可以重写为 z, not z, True, False

        2
  •  0
  •   Henri Menke    6 年前

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

    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
    

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

        3
  •  0
  •   Vora    6 年前

    模式匹配似乎是一种魅力。

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

    你可以免费看到你的真值表。