哈斯克尔递归函数



所以,我试图做的是递归地定义一个函数,如果我从金额a开始并每年收到p%的利息,那么它计算n年后我有多少钱。

interest (n,a,p)
| n > 0          = interest (n-1,a,p)
where a = (a*p)/100
| otherwise      = a

它给了我这个错误:

E:\Module1week3scripts.hs:35:2: error: parse error on input `|'
|
35 |  | otherwise      = a
|  ^

谁能告诉我我做错了什么? 谢谢。

where只能在所有守卫之后使用,并且适用于所有守卫。例如

f x y =
| x > 0     = g a + x   -- a is visible here
| otherwise = h a + y   -- and here
where a = x + y

此外,请注意,您的where a = (a*p)/100可能会导致不终止,因为a是根据自身递归定义的((a*p)/100(。您应该使用新的变量名称,例如a' = (a*p)/100. 一般来说,在 Haskell 中"重新定义"外部变量是一个坏主意:打开带有-Wall标志的警告有助于检测这些问题。

最后,请注意,您也可以使用let代替where,并在任何表达式中使用它。例如

f x y =
| x > 0 =
let a = x + y
in g a + x
| otherwise = y  -- a is not visible here

甚至可以写

(let a = x + y in g a) + x

虽然我不能推荐这种风格。

最新更新