如何进行简单的1行模式匹配?(让Bool摆脱模式匹配)

has*_*lHQ 2 haskell

在下面的代码,我如何检查-只有通过增加旁边一个班轮if-是否fooYes

data Asdf = Yes | No | Other

foo :: Asdf
foo = Yes

hello :: String
hello =
    if <check if foo is Yes> -- How?
     then "foo is Yes"
     else "foo isn't Yes"
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用case,但这个问题的关键是以某种方式得到Bool它.这对我在单元测试等方面很有用(case可能会很快变得非常混乱.)

lef*_*out 7

您可以使用

hello =
    if (case foo of {Yes -> True; _ -> False})
     then "foo is Yes"
     else "foo isn't Yes"
Run Code Online (Sandbox Code Playgroud)

但这肯定不是我推荐的.如果你可以使用EqWillem Van Onsem和bheklir建议的实例那么公平; 但一般来说我也会避免使用Eq.我不认为你应该努力获得一个布尔 - 布尔总是处理一些信息的信息最少的方式.case直接使用

hello =
    case foo of
     Yes -> "foo is Yes"
     _ -> "foo isn't Yes"
Run Code Online (Sandbox Code Playgroud)

更好 ; 如果在单元测试的集合中这太笨重,为什么不定义一个基本相同的合适的辅助函数呢?

  • 对于它的价值,您可以省略大括号:`case foo of Yes -&gt; True; _ -&gt; 错误`。 (2认同)

bhe*_*ilr 5

最简单的方法是derive (Eq)对你的类型:

data Asdf = Yes | No | Other deriving (Eq)
Run Code Online (Sandbox Code Playgroud)

然后你可以像平常一样使用==:

hello =
    if foo == Yes
        then "foo is Yes"
        else "foo isn't Yes"
Run Code Online (Sandbox Code Playgroud)

有一些可能有用的类型类,你可以得到额外的,喜欢Ord,Enum,Show,和Read.