Real World Haskell - 第3章 Part11 Conditional evaluation with guards

Real World HaskellHaskell を継続的に勉強中。


Defining Types, Streamlining Functions

Chapter 3. Defining Types, Streamlining Functions

ようやく 3章も終わり。

Conditional evaluation with guards
  • guard expression でパターンマッチに条件を付けられる
    • otherwise は常に True
lend3 amount balance
     | amount <= 0            = Nothing
     | amount > reserve * 0.5 = Nothing
     | otherwise              = Just newBalance
    where reserve    = 100
          newBalance = balance - amount

以前の myDrop を guard で書き直し。
これが、

myDrop n xs = if n <= 0 || null xs
              then xs
              else myDrop (n - 1) (tail xs)

こうなる。

niceDrop n xs | n <= 0 = xs
niceDrop _ []          = []
niceDrop n (_:xs)      = niceDrop (n - 1) xs