갈루아의 반서재

728x90

Guards are a way of testing whether some property of a value (or several of them) are true or false. 

We're going to make a simple function that berates you differently depending on your BMI.

  1. bmiTell :: (RealFloat a) => a -> String  
  2. bmiTell bmi  
  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!"  

Guards are indicated by pipes that follow a function's name and its parameters. If it evaluates to True, then the corresponding function body is used. If it evaluates to False, checking drops through to the next guard and so on. The last guard is otherwise. otherwise is defined simply as otherwise = True and catches everything. 

Of course we can use guards with functions that take as many parameters as we want.

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

Note that there's no = right after the function name and its parameters, before the first guard.

  1. max' :: (Ord a) => a -> a -> a  
  2. max' a b   
  3.     | a > b     = a  
  4.     | otherwise = b  

Guards can also be written inline.

  1. max' :: (Ord a) => a -> a -> a  
  2. max' a b | a > b = a | otherwise = b  

Let's implement our own compare by using guards.

  1. myCompare :: (Ord a) => a -> a -> Ordering  
  2. `myCompare` b  
  3.     | a > b     = GT  
  4.     | a == b    = EQ  
  5.     | otherwise = LT  
  1. ghci> 3 `myCompare` 2  
  2. GT  


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




728x90