在Unit值上使用case表达式只是为了使用守卫是好的风格吗?

b0f*_*0fh 15 haskell

测试几个布尔表达式的推荐方法是什么?

我一直在用这个:

case () of () | test1 -> value1
              | test2 -> value2
              | otherwise -> value3
Run Code Online (Sandbox Code Playgroud)

这是好风格吗?有更漂亮的方式吗?

Art*_*yom 23

可以使用函数模拟此模式 - 例如,condControl.Conditional:

signum x = cond [(x > 0     ,  1)
                ,(x < 0     , -1)
                ,(otherwise ,  0)]
Run Code Online (Sandbox Code Playgroud)

不过,我不能称之为特别漂亮.


在下一个GHC,我们将能够使用多方式,如果,万岁!(刚发现)

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


fuz*_*fuz 7

这是我经常看到的一个习惯用法,因为Haskell缺少一个没有匹配的案例的正确语法.为了让我的意图更加清晰,我通常会故意匹配undefined:

case undefined of
  _ | foo       -> bar
    | baz       -> quux
    | otherwise -> chunkyBacon
Run Code Online (Sandbox Code Playgroud)