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

Ste*_*and 2 haskell boolean tuples

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

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"
Run Code Online (Sandbox Code Playgroud)

但是这不会编译:

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"
Run Code Online (Sandbox Code Playgroud)

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

the*_*eye 5

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

Couldn't match expected type `Bool'
            with actual type `(Bool, Bool, Bool, Bool)'
Run Code Online (Sandbox Code Playgroud)

你最好定义这样的功能

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"
Run Code Online (Sandbox Code Playgroud)

此外,您没有涵盖所有情况.所以,你可以这样做

chooseAction tuple_of_bools = "NONE"
Run Code Online (Sandbox Code Playgroud)

如果没有任何模式匹配,那么将执行最后一个模式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"
Run Code Online (Sandbox Code Playgroud)