Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching using cases vs functions

Tags:

haskell

Say I want to define a function

applyTwice :: (Int -> Int) -> Int -> Int
applyTwice f x = case f x of
                   0 -> 0
                   y -> f y

I could also define that same function as

applyTwice f x = g (f x)
  where g 0 = 0
        g y = f y

Those would both do the same thing, and maybe one or the other is more readable sometimes, but is there any real difference between the two. Is one just syntactic sugar for the other? Are there weird cases where one works but the other doesn't?

The only potential differences I can think of are that in the second function I could give g a type signature if I felt like it, and using a helper function might save me from a nested case statement if I wanted to pattern match multiple variables.

like image 589
genisage Avatar asked Aug 23 '14 04:08

genisage


1 Answers

When you write a function like

g 0 = 0
g y = f y

The compiler translates this to

g x = case x of
    0 -> 0
    y -> f y

You can check this by compiling with ghc -ddump-simpl my_file.hs and then digging through the generated core. So really, pattern matching is just syntactic sugar for a case statement. Use whichever you find most readable, both are pretty standard.

like image 152
bheklilr Avatar answered Oct 14 '22 12:10

bheklilr