Haskell递归函数

Haskell递归函数,haskell,recursion,Haskell,Recursion,因此,我试图递归地定义一个函数,计算我在n年后有多少钱,如果我从a开始,每年收到p的利息百分比 interest (n,a,p) | n > 0 = interest (n-1,a,p) where a = (a*p)/100 | otherwise = a 这给了我一个错误: E:\\Module1\week3\scripts.hs:35:2: error: parse error on input `|' | 35 | | oth

因此,我试图递归地定义一个函数,计算我在n年后有多少钱,如果我从a开始,每年收到p的利息百分比

interest (n,a,p)
 | n > 0          = interest (n-1,a,p)
       where a = (a*p)/100
 | otherwise      = a
这给了我一个错误:

E:\\Module1\week3\scripts.hs:35:2: error: parse error on input `|'
   |
35 |  | otherwise      = a
   |  ^
谁能告诉我我做错了什么?
谢谢。

其中
只能在所有防护装置之后使用,并适用于所有防护装置。比如说

f x y =
  | x > 0     = g a + x   -- a is visible here
  | otherwise = h a + y   -- and here
  where a = x + y
f x y =
  | x > 0 =
     let a = x + y
     in g a + x
  | otherwise = y  -- a is not visible here
此外,请注意,
其中a=(a*p)/100
可能会导致非终止,因为
a
是根据自身递归定义的(
(a*p)/100
)。您应该使用新的变量名,例如
a'=(a*p)/100
。 在Haskell中“重新定义”外部变量通常是一个坏主意:使用
-Wall
标志打开警告有助于检测这些问题

最后,请注意,您还可以使用
let
而不是
where
,并在任何表达式中使用它。比如说

f x y =
  | x > 0     = g a + x   -- a is visible here
  | otherwise = h a + y   -- and here
  where a = x + y
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

尽管我不能推荐这种风格。

其中
只能在所有防护装置之后使用,并且适用于所有防护装置。比如说

f x y =
  | x > 0     = g a + x   -- a is visible here
  | otherwise = h a + y   -- and here
  where a = x + y
f x y =
  | x > 0 =
     let a = x + y
     in g a + x
  | otherwise = y  -- a is not visible here
此外,请注意,
其中a=(a*p)/100
可能会导致非终止,因为
a
是根据自身递归定义的(
(a*p)/100
)。您应该使用新的变量名,例如
a'=(a*p)/100
。 在Haskell中“重新定义”外部变量通常是一个坏主意:使用
-Wall
标志打开警告有助于检测这些问题

最后,请注意,您还可以使用
let
而不是
where
,并在任何表达式中使用它。比如说

f x y =
  | x > 0     = g a + x   -- a is visible here
  | otherwise = h a + y   -- and here
  where a = x + y
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

尽管我不能推荐这种风格。

我成功地使用了if而不是guards。我也会这样尝试。非常感谢你!我成功地用if代替了警卫。我也会这样尝试。非常感谢你!虽然这不是错误,但在Haskell中定义不“curry”的函数是相当少见的。通常,函数被定义为
interest n a p=…
,因此用
interest(n-1)a p
调用。虽然这不是错误,但定义非“curried”的函数在Haskell中相当少见。通常,这些函数被定义为
interest n a p=…
,因此用
interest(n-1)a p
调用。