What is the recommended way of testing several boolean expressions ?
I've been using this:
case () of () | test1 -> value1
| test2 -> value2
| otherwise -> value3
Is this good style ? is there a prettier way ?
This pattern can be simulated with a function — for instance, cond
from Control.Conditional:
signum x = cond [(x > 0 , 1)
,(x < 0 , -1)
,(otherwise , 0)]
I can’t call it particularly beautiful, though.
In next GHC we will be able to use multi-way if, hooray! (just found it out)
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"
This is an idiom I see pretty often since Haskell lacks a proper syntax for a case without matching. To make my intentions clearer, I usually intentionally match undefined
:
case undefined of
_ | foo -> bar
| baz -> quux
| otherwise -> chunkyBacon
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With