haskell中有两种定义局部变量的方法let和where,方法分别如下
roots a b c = ((-b + det) / (a2), (-b - det) / (a2)) where det = sqrt(b*b-4*a*c) a2 = 2*a
roots a b c = let det = sqrt (b*b - 4*a*c) a2 = 2*a in ((-b + det) / a2, (-b - det) / a2)
这两种方法都可以使全局变量定义失效
det = "Hello World" roots a b c =((-b + det) / (2*a), (-b - det) / (2*a)) where det = sqrt(b*b-4*a*c) roots' a b c= let det = sqrt(b*b-4*a*c) in ((-b + det) / (2*a), (-b - det) / (2*a)) f _ = det *Main> roots 1 3 2 (-1.0,-2.0) *Main> roots' 1 3 2 (-1.0,-2.0) *Main> f 'a' "Hello World"
对于let和where混用,那么是let的优先级高,也就是说优先使用let定义的变量,而不是where定义的变量,比如
f x = let y = x+1 in y where y = x+2 *Main> f 10 11
等于11而不是12
对于let和where,同样也支持模式匹配,例如
showmoney2 a b c= (create a 0 0)+(create 0 b 0)+(create 0 0 c) where create 1 _ _=1 create _ 1 _=2 create _ _ 1=3 showmoney a b c= let create 1 _ _=1 create _ 1 _=2 create _ _ 1=3 in (create a 0 0) + (create 0 b 0) + (create 0 0 c) *Main> showmoney 1 1 1 6 *Main> showmoney2 1 1 1 6