Let
let
绑定与
where
绑定很相似。
where
绑定是在函数底部定义名字,对包括所有
guard
在内的整个函数可见。
let 绑定 则是个表达式,允许你在任何位置定义局部变量,而对不同的
guard
不可见。
cylinder :: (RealFloat a) => a -> a -> a
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^2
in sideArea + 2 * topArea
若要在一行中绑定多个名字,再将它们排成一列显然是不可以的。不过可以用分号将其分开。
ghci> (let a = 100; b = 200; c = 300 in a*b*c, let foo="Hey "; bar = "there!" in foo ++ bar)
(6000000,"Hey there!")
Case
模式匹配本质上不过就是 case 语句的语法糖而已
case语法:
describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of [] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
模式匹配:
describeList :: [a] -> String
describeList xs = "The list is " ++ what xs
where what [] = "empty."
what [x] = "a singleton list."
what xs = "a longer list."