1

I've written a simple function in haskell that is non tail recursive that sums up the values inside a list where:

nonTailRecursiveSum :: [Integer] -> Integer
nonTailRecursiveSum [] = 0 --base case
nonTailRecursiveSum (x:xs) = x + sum xs

But what I'm trying to do now is to implement the same function but using tail recursion. For what i know, tail recursion performs the recursive call at the final step so i tried something like:

tailRecursiveSum :: [Integer] -> Integer
tailRecursiveSum [] = 0
tailRecursiveSum (x:xs) = aux_f(x) + tailRecursiveSum xs
.
.

But i got lost in the midway as I'm not familiar with tail recursion in Haskell. Could anyone assist me on the continuation of the tail recursive version of the code?

2
  • sum (x:xs) = aux xs x where aux (x:xs) total = aux xs (x + total) Commented Nov 3, 2018 at 5:57
  • 1
    For the recursion to be tail recursion, you need your cases to be similar to tailRecursiveFunction something = tailRecursiveFunction somethingElse. Commented Nov 3, 2018 at 6:27

1 Answer 1

1

Playing with it for a bit,

sum (x:y:xs) = x + sum (y:xs)
             = x + (y + sum xs)
             = (x + y) + sum xs

g a b = a + sum b

sum (x:y:xs) = g x (y:xs)
             = x + g y xs
             = g (x+y) xs   -- !!!

the last one is in tail recursive form! We thus just define

sum xs = g 0 xs
  where
  g acc [] = ...
  g acc (x:xs) = g (acc + ...) ...

Fill in the blanks!

Sign up to request clarification or add additional context in comments.

4 Comments

You can start with sum (x:xs) = g x xs immediately to avoid 0 + .... (Which only works because (+) 0 is essentially id for numeric types.)
but then I have to handle the [] case separately. With the explicit 0. It's unavoidable.
What do you mean by the last one (of the first code block) being in tail recursive form?
@DavidYoung in g x (y:xs) = g (x+y) xs, call to g is a tail call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.