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?
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.
No, it is not possible to express all recursion as tail recursion unless you do supplement the tail recursion with other control flow mechanisms.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With