CTM: Exercises of Chapter 1 (Exercise 5)

Posted by urban Sat, 02 Apr 2005 11:37:00 GMT

The problem

Lazy evaluation. Section 1.8 defines a lazy function Ints that lazily calculates an infinite list of integers. Let us define a function that calculates the sum of a list of integers:


fun {SumList L}
   case L of X|L1 then X+{SumList L1}
   else 0 end
end

What happens if we call {SumList {Ints 0}}? Is this a good idea?

My solution

When calling {{SumList {Ints 0}} we end up with an infinite recursion because we want to add up all numbers in the list {Ints 0}. This is of course not possible as each call to {SumList L1} (in the second line of the SumList function) generates a successive element of the list through X|L1.

Tags , ,

Comments are disabled