Real World Haskell - 第3章 Part8 Introducing local variables

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


Defining Types, Streamlining Functions

Chapter 3. Defining Types, Streamlining Functions

Introducing local variables
  • let か where でローカル変数を定義できる
lend amount balance = let reserve    = 100
                          newBalance = balance - amount
                      in if balance < reserve
                         then Nothing
                         else Just newBalance
lend2 amount balance = if amount < reserve * 0.5
                       then Just newBalance
                       else Nothing
    where reserve    = 100
          newBalance = balance - amount
  • shadowing
    • "the inner x is hiding, or shadowing, the outer x. It has the same name, but a different type and value."
    • GHC には -fwarn-name-shadowing オプションがある
bar = let x = 1
      in ((let x = "foo" in x), x)
ghci> bar
("foo",1)
  • ローカル変数と同様にローカル関数を定義できる
pluralise :: String -> [Int] -> [String]
pluralise word counts = map plural counts
    where plural 0 = "no " ++ word ++ "s"
          plural 1 = "one " ++ word
          plural n = show n ++ " " ++ word ++ "s"
itemName = "Weighted Companion Cube"