At the moment I'm trying to learn Haskell with the online tutorial Learn you a Haskell. In the chapter "Syntax in Functions" the author wrote "You can also use where bindings to pattern match!". After that there's a part of a code example, but I don't know where pattern matching is used together with the new where binding. Because the first part of the code block was shortened ("We could have rewritten the where section of our previous function as"), you can only infer it but I think that I chose the correct part.
The function:
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
The new where section to replace:
where bmi = weight / height ^ 2
(skinny, normal, fat) = (18.5, 25.0, 30.0)
Because I want to understand all code examples and syntax methods of Haskell explained in this tutorial, I hope that someone can explain where pattern matching is used in here and how does it in here works. The problem for me is that I only see the guards and one pattern which binds everything to weight and height.
The line
(skinny, normal, fat) = (18.5, 25.0, 30.0)
is a pattern binding -- the pattern is (skinny, normal, fat)
, a tuple pattern that binds three names. You can also use other kinds of patterns in a where
(and let
), for example:
head' :: [a] -> a
head' list = x
where
x : xs = list
Here x : xs
is a pattern that binds two names. Of course it is unnecessary in this case, we could have just put the pattern in the argument. But it does come in handy once in a while.