interesting example of lazyness/ghc optimisation
Christian Brolin
Christian.Brolin@carmen.se
Thu, 01 Mar 2001 16:41:15 +0100
Ketil Malde wrote:
>
> There's something that I've been wanting to ask sombody about, since
> it isn't terribly clear to me. Blatantly hijacking a function from
> Julian's code:
>
> > runRandom last max num
> > | num > 1 = runRandom (fst new) max (num-1)
> > | otherwise = snd new
>
> While ifs are perhaps more intuitive when there are only two choices
> (like here!), and pattern matching matches on the type of arguments
> and not (only) their values,
>
> What's the difference between the pipe-syntax, and a case statement,
> i.e. writing the function as
>
> runRandom last max num = case num of
> 1 -> runRandom ....
> otherwise -> snd new
>
> Is there a practical difference, and if not, why are there two ways to
> skin this particular cat?
You shouldn't compare case expressions with guards. Guards are used
together with patterns, while case expressions are using patterns.
Hence, it is possible to use guards in case expressions. The question is
why *patterns* are allowed with function definitions. I guess the answer
is syntax sugar.
example:
f [a] | a>0 = 1
| a<0 = 2
f _ = 3 -- [], [0], [a:as]
Can be written as:
f x = case x of
[a] | a>0 -> 1
| a<0 -> 2
_ -> 3
--
Christian Brolin