Since we repeat the same expression three times, it would be ideal if we could calculate it once, bind it to a name and then use that name instead of the expression.
- bmiTell :: (RealFloat a) => a -> a -> String
- bmiTell weight height
- | bmi <= 18.5 = "You're underweight, you emo, you!"
- | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"
- | bmi <= 30.0 = "You're fat! Lose some weight, fatty!"
- | otherwise = "You're a whale, congratulations!"
- where bmi = weight / height ^ 2
We put the keyword where after the guards (usually it's best to indent it as much as the pipes are indented) and then we define several names or functions.
- 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 names we define in the where section of a function are only visible to that function.
Notice that all the names are aligned at a single column.
where bindings aren't shared across function bodies of different patterns.
You can also use where bindings to pattern match!
- ...
- where bmi = weight / height ^ 2
- (skinny, normal, fat) = (18.5, 25.0, 30.0)
where bindings can also be nested.
본 카테고리의 내용은 Learn You a Haskell for Great Good! 의 내용을 학습을 위해 요약한 것입니다.
'프로그래밍 Programming' 카테고리의 다른 글
Functional Programming with Haskell - 패러다임 (0) | 2018.03.24 |
---|---|
Functional Programming with Haskell - Interacting with Haskell (0) | 2018.03.22 |
Haskell Operators and other Lexical Notation (0) | 2018.03.17 |
Haskell_006 Guards (0) | 2018.03.17 |
Haskell_005 Pattern matching (0) | 2018.03.17 |