一个布尔元组可以在防护中匹配,比如模式匹配吗?

时间:2015-02-28 17:20:49

标签: haskell boolean tuples

我尝试创建一个返回不同字符串的函数,具体取决于boolean元组中的值

chooseAction :: (Bool , Bool , Bool , Bool) -> String 
chooseAction (isJump ,isAcceleration ,isDeceleration ,isSpeedOk) 
        | (True ,False, False, False) = "JUMP"
        | (False ,True, False, False) = "SPEED"
        | (False ,False, True, False) = "SLOW"
        | (False ,False ,False, True) = "WAIT"

然而,这不会编译:

Couldn't match expected type `Bool'
            with actual type `(Bool, Bool, Bool, Bool)'
In the expression: (True, False, False, False)
In a stmt of a pattern guard for
               an equation for `chooseAction':
  (True, False, False, False)
In an equation for `chooseAction':
    chooseAction (isJump, isAcceleration, isDeceleration, isSpeedOk)
      | (True, False, False, False) = "JUMP"
      | (False, True, False, False) = "SPEED"
      | (False, False, True, False) = "SLOW"
      | (False, False, False, True) = "WAIT"

在定义这样的函数时我做错了什么?

2 个答案:

答案 0 :(得分:5)

守卫表达式必须评估为Bool值,但在您的情况下,您有一些Bools元组。这就是它抛出错误的原因

Couldn't match expected type `Bool'
            with actual type `(Bool, Bool, Bool, Bool)'

最好定义像这样的函数

chooseAction::(Bool, Bool, Bool, Bool) -> String
chooseAction (True, False, False, False) = "JUMP"
chooseAction (False, True, False, False) = "SPEED"
chooseAction (False, False, True, False) = "SLOW"
chooseAction (False, False, False, True) = "WAIT"

此外,您没有涵盖所有案件。所以,你可以像这样覆盖

chooseAction tuple_of_bools = "NONE"

如果所有模式都不匹配,则执行最后一个模式以获得NONE。或者,如果您希望按照它的方式定义它,那么只需更改比较,就像这样

chooseAction:: (Bool, Bool, Bool, Bool) -> String
chooseAction bools
        | bools == (True ,False, False, False) = "JUMP"
        | bools == (False ,True, False, False) = "SPEED"
        | bools == (False ,False, True, False) = "SLOW"
        | bools == (False ,False ,False, True) = "WAIT"
        | otherwise = "NONE"

答案 1 :(得分:3)

使用模式匹配:

chooseAction :: (Bool , Bool , Bool , Bool) -> String 
chooseAction (True ,False, False, False) = "JUMP"
chooseAction (False ,True, False, False) = "SPEED"
chooseAction (False ,False, True, False) = "SLOW"
chooseAction (False ,False ,False, True) = "WAIT"
chooseAction _ = error "This should not happen" -- if sequence is something else