Thursday, September 08, 2011

Scala By Example Chapter 5 Solutions - Exercise 5.2.1

Exercise 5.2.1 1. The sum function uses a linear recursion. Can you write a tail- recursive one by filling in the ??’s?

The key is to understand that converting linear recursion to a tail-recursive version involves carrying over a computed value over to the next iteration. Also, note that the call to the iter function at the end need not take in a and b as parameters directly but can be computed values. Thats what facilitates the tail-recursive version. Here's my solution to the exercise.

No comments: