Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does tail recursion necessarily need an accumulator?

For instance, since the following function don't have an accumulator, is it still tail recursive?

belong:: (Ord a) => a -> [a] -> Bool
belong a [] = False
belong a (h:t) 
    | a == h = True
    | otherwise = belong a t

All the computations in the function are processed before the recursive call, is it a sufficient condition to be considered tail recursive?

like image 530
user1493813 Avatar asked Dec 18 '12 19:12

user1493813


People also ask

What makes a function tail recursive?

A function is tail-recursive if it ends by returning the value of the recursive call. Keeping the caller's frame on stack is a waste of memory because there's nothing left to do once the recursive call returns its value. So, instead of allocating a new frame for the call, we can reuse the existing one.

Can all recursion be tail recursion?

No, it is not possible to express all recursion as tail recursion unless you do supplement the tail recursion with other control flow mechanisms.

How is tail recursion implemented?

Here we will see what is tail recursion. The tail recursion is basically using the recursive function as the last statement of the function. So when nothing is left to do after coming back from the recursive call, that is called tail recursion.

Is tail recursion just iteration?

A tail recursive method is one way to specify an iterative process. Iteration is so common that most programming languages provide special constructs for specifying it, known as loops.


1 Answers

Tail recursion does not necessarily need an accumulator. Accumulators are used in tail recursion as a way of communicating a partial result down through the recursive call chain without requiring extra space to be used at each level of the recursion. For example, the canonical tail recursive factorial function needs an accumulator to propagate the partial product built up so far. However, if you don't need to communicate any information from a recursive call down to its subcall, then the accumulator isn't necessary.

The function you've provided is indeed tail recursive, but it doesn't need or use an accumulator. When searching for an element in a list, the recursion doesn't need to remember that all of the elements it has looked at so far aren't equal to the particular element being searched for. It just needs to know what element to look for and what list to search.

Hope this helps!

like image 54
templatetypedef Avatar answered Oct 20 '22 08:10

templatetypedef