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.
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.
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