【问题标题】:Haskell Recursion FunctionHaskell 递归函数
【发布时间】:2019-02-28 05:14:55
【问题描述】:

所以,我尝试做的是递归地定义一个函数,如果我从一个金额开始,它会计算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
   |  ^

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

【问题讨论】:

  • 虽然这不是错误,但定义不是“curried”的函数在 Haskell 中相当少见。通常函数定义为interest n a p = ...,因此使用interest (n-1) a p 调用。

标签: haskell recursion


【解决方案1】:

where 只能用在all这些守卫之后,并且适用于所有守卫。比如

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

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

【讨论】:

  • 我成功地使用了 if 而不是守卫。我也会尝试这种方式。非常感谢!
猜你喜欢
  • 2011-02-14
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
相关资源
最近更新 更多