Real World Haskell - 第3章 Part8 Introducing local variables
Real World Haskell で Haskell を継続的に勉強中。
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
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"