Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good style to use a case expression on a Unit value just to use guards?

Tags:

haskell

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 ?

like image 222
b0fh Avatar asked Jul 23 '12 21:07

b0fh


2 Answers

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" 
like image 198
Artyom Avatar answered Sep 28 '22 18:09

Artyom


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
like image 39
fuz Avatar answered Sep 28 '22 19:09

fuz