测试几个布尔表达式的推荐方法是什么?
我一直在使用这个:
case () of () | test1 -> value1
| test2 -> value2
| otherwise -> value3
这是好风格吗?有没有更漂亮的方法?
测试几个布尔表达式的推荐方法是什么?
我一直在使用这个:
case () of () | test1 -> value1
| test2 -> value2
| otherwise -> value3
这是好风格吗?有没有更漂亮的方法?
这种模式可以用一个函数来模拟——例如,cond
来自Control.Conditional:
signum x = cond [(x > 0 , 1)
,(x < 0 , -1)
,(otherwise , 0)]
不过,我不能说它特别漂亮。
在下一个 GHC 中,我们将能够使用多路 if,万岁!(刚刚发现)
f t x = if | l <- length t, l > 2, l < 5 -> "length is 3 or 4"
| Just y <- lookup x t -> y
| False -> "impossible"
| null t -> "empty"
这是我经常看到的一个习惯用法,因为 Haskell 缺少一个正确的语法来处理没有匹配的情况。为了使我的意图更清楚,我通常故意匹配undefined
:
case undefined of
_ | foo -> bar
| baz -> quux
| otherwise -> chunkyBacon
您还可以对元组内的一系列表达式进行模式匹配
case (test1,test2) of
(True,_) -> value1
(_,True) -> value2
_ -> value3