Example 4.7, tail recursive version