简体   繁体   English

该尾递归Haskell函数的错误在哪里?

[英]Where is the mistake in this tail recursive Haskell function?

I have to implement a sum function in Haskell in two ways. 我必须以两种方式在Haskell中实现sum函数。 One function with tail recursion and the other without tail recursion. 一个函数具有尾递归,而另一个函数没有尾递归。

Here is the one without tail recursion and it works perfectly 这是没有尾递归的,它完美地工作

sum1 x = if x==0 then 0 else x + sum1(x-1)

Here is my attempt with tail recursion and it doesn't work: 这是我尝试的尾递归,但不起作用:

sum2 x = help 0 y
help x y = if y==0 then x else help(x+y,y-1)

Can someone point out the mistake? 有人可以指出错误吗?

Your line: 您的电话:

help x y = if y==0 then x else help(x+y,y-1)

is not the correct syntax for calling a function. 不是调用函数的正确语法。 Because here the Haskell compiler will interpret it as: 因为在这里Haskell编译器会将其解释为:

help x y = if y==0 then x else help (x+y,y-1)
--                                  ^ a tuple

Instead you should write: 相反,您应该写:

help x y = if y==0 then x else help (x+y) (y-1)
--                                  ^ two arguments

Furthermore you can also use guards, like: 此外,您还可以使用防护装置,例如:

helper x y | y == 0 = x
           | otherwise = help (x+y) (y-1)

Finally there is also an error in the first line of sum2 . 最后, sum2的第一行中也有一个错误。 It should be x instead of y : 应该是x而不是y

sum2 x = help 0 x

So in full, we get: 因此,总的来说,我们得到:

sum2 x = help 0 x
helper s x | x == 0 = s
           | otherwise = help (s+x) (x-1)

I also renamed y in the helper to x and x to s (as in s um) to make it less confusing (kudos to @Bergi for commenting on this). 我也改名yhelperxxs (如s UM),使其不易混淆(荣誉给@Bergi的评论这一点)。

Or use an eta reduction : 或使用eta减少量

sum2 = help 0

Finally note that you do not need recursion for this. 最后请注意,您不需要为此进行递归。 An implementation that would work faster is the following: 以下是一种可以更快运行的实现:

sum3 x = div (x*(x+1)) 2

Since: 以来:

n
---
\       (n+1) n
/   i = -------
---        2
i=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM