[英]Tail recursion in Haskell for a function
I am trying to learn Haskell and I read about tail recursions. 我正在尝试学习Haskell,并且阅读了有关尾部递归的信息。 For example I can write the sum function this way :
例如,我可以这样编写sum函数:
sum :: Num a => [a] -> a
sum [] = 0
sum (x:xs) = x + summe xs
But also this way 也是这样
summe':: Num a => [a] -> a
summe' x = iterate x 0
where
iterate x y | null x = 0 + y
| otherwise = iterate (tail x) (head x + y)
Could someone tell me how to do it with this function? 有人可以告诉我如何使用此功能吗? I am lost
我搞不清楚了
f :: Integer -> Integer
f 0 = 0
f n = n * f (n-1) + n
In order to rewrite the following function using tail-recursion: 为了使用尾递归重写以下功能:
f :: Integer -> Integer
f 0 = 0
f n = n * f (n-1) + n
the same approach, which used in summe'
can be used. 可以使用在
summe'
中使用的相同方法。
The idea is to start from zero and increment the value until n
is reached: 这个想法是从零开始,然后递增值直到达到
n
:
f :: Integer -> Integer
f n = iterate 0 0
where
f' x sum = x * sum + x
iterate x sum | x == n = f' n sum
| otherwise = iterate (x + 1) (f' x sum)
Thus, if n
is reached, evaluate the function with n
and the accumulated sum; 因此,如果
n
达到,评估与所述功能n
和累加和; otherwise, calculate the function with intermediate sum and value and pass it to the next iteration. 否则,请使用中间的总和和值来计算函数,然后将其传递给下一个迭代。
Well, flipping the "time direction" in fn = n * f (n-1) + n
by letting n = k + 1
, we have 好吧,通过让
n = k + 1
翻转fn = n * f (n-1) + n
的“时间方向”,我们有
f (k+1) = (k+1) * f k + (k+1)
next fk k = (k+1) * fk + (k+1)
and thus 因此
f n = iterate 0 0
where
iterate k fk | k==n = fk
| otherwise = ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.