haskell中有两种定义局部变量的方法let和where,方法分别如下
roots a b c = ((-b + det) / (a2), (-b - det) / (a2))
where det = sqrt(b*b-*a*c)
a2 = *a
roots a b c = let det = sqrt (b*b - *a*c)
a2 = *a
in ((-b + det) / a2, (-b - det) / a2)
这两种方法都可以使全局变量定义失效
det = "Hello World"
roots a b c =((-b + det) / (*a), (-b - det) / (*a))
where det = sqrt(b*b-*a*c)
roots' a b c=
let det = sqrt(b*b-*a*c)
in ((-b + det) / (*a), (-b - det) / (*a))
f _ = det
*Main> roots
(-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+
in y
where y = x+
*Main> f
等于11而不是12
对于let和where,同样也支持模式匹配,例如
showmoney2 a b c=
(create a )+(create b )+(create c)
where create _ _=
create _ _=
create _ _ = showmoney a b c=
let create _ _=
create _ _=
create _ _ =
in (create a ) + (create b ) + (create c)
*Main> showmoney *Main> showmoney2