haskellの関数構文

haskellの関数構文メモ
パターンマッチ 引数を定数で場合分けできる

1
2
3
4
yourName :: String -> String
yourName "poo" = "Hi, poo"
yourName "boo" = "Hi, boo"
yourName x = "invalid name"

ガード 引数を範囲で場合分けできる

1
2
3
4
5
6
yourMemory :: 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
7
yourMemory' :: 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
2
3
4
5
6
7
8
yourMemory'' :: Int -> Int -> String
yourMemory'' val1 val2
| memory < low = "low spec"
| memory < com = "common spec"
| memory < high = "hight spec"
| otherwise = "invalid value"
where memory = val1 + val2
(low, com, high) = (4,8,16)

whereの中に関数をかける

1
2
3
sqArea :: [(Double, Double)] -> [Double]
sqArea s = [cal w h | (w, h) <- s]
where cal weight height = weight * height

let式はin以降が値

1
2
3
4
cylinder 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)]