갈루아의 반서재

728x90


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. 

  1. bmiTell :: (RealFloat a) => a -> a -> String  
  2. bmiTell weight height  
  3.     | bmi <= 18.5 = "You're underweight, you emo, you!"  
  4.     | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!"  
  5.     | bmi <= 30.0 = "You're fat! Lose some weight, fatty!"  
  6.     | otherwise   = "You're a whale, congratulations!"  
  7.     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.

  1. bmiTell :: (RealFloat a) => a -> a -> String  
  2. bmiTell weight height  
  3.     | bmi <= skinny = "You're underweight, you emo, you!"  
  4.     | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"  
  5.     | bmi <= fat    = "You're fat! Lose some weight, fatty!"  
  6.     | otherwise     = "You're a whale, congratulations!"  
  7.     where bmi = weight / height ^ 2  
  8.           skinny = 18.5  
  9.           normal = 25.0  
  10.           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

  1. ...  
  2. where bmi = weight / height ^ 2  
  3.       (skinny, normal, fat) = (18.525.030.0)  

where bindings can also be nested.



본 카테고리의 내용은 Learn You a Haskell for Great Good! 의 내용을 학습을 위해 요약한 것입니다.




728x90