haskell中有兩種定義局部變量的方法let和where,方法分別以下spa
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)
這兩種方法均可以使全局變量定義失效code
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定義的變量,好比blog
f x = let y = x+1 in y where y = x+2 *Main> f 10 11
等於11而不是12class
對於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