[英]Haskell non-tail recursion
I want to know if this represents a tail-recursion. 我想知道这是否代表尾递归。 And if it isn't how can I do it. 如果不是我怎么能这样做。
countP :: [a] -> (a->Bool) -> Int
countP [] _ = 0
countP (x:xs) p = countP_aux (x:xs) p 0
countP_aux [] _ _ = 0
countP_aux (x:xs) p acumul
|p x==True = (countP_aux xs p (acumul))+1
|otherwise = (countP_aux xs p (acumul))
countP [1,2,3] (>0)
3
(72 reductions, 95 cells)
This exercise show how many values in a list are verified by p condition. 此练习显示列表中有多少值由p条件验证。 Thanks 谢谢
This is not tail recursive because of 由于这不是尾递归
(countP_aux xs p (acumul))+1
Tail calls should return the result of the recursive call, rather than doing calculation with the result of the recursive call. 尾调用应返回递归调用的结果,而不是使用递归调用的结果进行计算。
You can convert a non-tail recursive function to be tail-recursive by using an accumulator where you perform the additional work, ie 您可以使用累加器将非尾递归函数转换为尾递归,您可以在其中执行其他工作,即
Say you have a simple counting function 假设你有一个简单的计数功能
f a
| a < 1 = 0
| otherwise = f (a-1) + 1
You can make it tail recursive like so: 你可以像往常那样使尾递归:
f' acc a =
| a < 1 = acc
| otherwise = f' (acc + 1) (a-1)
f = f' 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.