haskellの関数構文メモ
パターンマッチ 引数を定数で場合分けできる1
2
3
4yourName :: String -> String
yourName "poo" = "Hi, poo"
yourName "boo" = "Hi, boo"
yourName x = "invalid name"
ガード 引数を範囲で場合分けできる1
2
3
4
5
6yourMemory :: Int -> Int -> String
yourMemory val1 val2
| val1+val2 < 4 = "low spec"
| val1+val2 < 8 = "common spec"
| val1+val2 < 16 = "high spec"
| otherwise = "invalid value"
他の書き方1
2
3
4
5
6
7yourMemory' :: Int -> Int -> String
yourMemory' val1 val2
| memory < 4 = "low spec"
| memory < 8 = "common spec"
| memory < 16 = "high spec"
| otherwise = "invalid value"
where memory = val1 + val2
1 | yourMemory'' :: Int -> Int -> String |
whereの中に関数をかける1
2
3sqArea :: [(Double, Double)] -> [Double]
sqArea s = [cal w h | (w, h) <- s]
where cal weight height = weight * height
let式はin以降が値1
2
3
4cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
また、letはローカルスコープに関数を作る時に使える1
[let listManage x = [y * x | y <- [1..10]] in (listManage 1, listManage 2, listManage 3)]