Pattern matching using cases versus functions

Say I want to define a function

applyTwice :: (Int -> Int) -> Int -> Int applyTwice fx = case fx of 0 -> 0 y -> fy 

I could also define the same function as

 applyTwice fx = g (fx) where g 0 = 0 gy = fy 

Those will do the same, and perhaps one or the other is read sometimes, but is there any real difference between the two. Is this one syntactic sugar for another? Are there any strange cases when one is working and the other is not?

The only potential differences that I can imagine is that in the second function, I could give a signature like ga if I liked it, and using a helper function could save me from the nested case statement, if I wanted to so that the pattern matches multiple variables.

+6
source share
1 answer

When you write a function like

 g 0 = 0 gy = fy 

The compiler translates this to

 gx = case x of 0 -> 0 y -> fy 

You can verify this by compiling with ghc -ddump-simpl my_file.hs and then going through the generated kernel. So really, pattern matching is just syntactic sugar for the case statement. Use what you consider the most readable, both are pretty standard.

+13
source

Source: https://habr.com/ru/post/974239/


All Articles