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

时间:2017-07-24 13:53:47

标签: haskell

在以下代码中,我如何检查 - 仅在if旁边添加一行内容 - foo是否为Yes

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"

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

2 个答案:

答案 0 :(得分:7)

您可以使用

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

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

hello =
    case foo of
     Yes -> "foo is Yes"
     _ -> "foo isn't Yes"

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

答案 1 :(得分:5)

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

data Asdf = Yes | No | Other deriving (Eq)

然后您可以像正常一样使用==

hello =
    if foo == Yes
        then "foo is Yes"
        else "foo isn't Yes"

您可以添加许多可能有用的类型类,例如OrdEnumShowRead

相关问题