From Paul Prescod: papresco@cantor.math.uwaterloo.ca

I'm learning ML from your tutorial. It is very well done. I like it a lot and am learning a lot. One quibble:

"Note that in practice execution of this function requires stack space for each call and so in terms of memory use the execution of a recursive program is less efficient than a corresponding iterative program. As functional advocates we take a perverse pride in this."

That statement isn't true for all functional languages or all functional advocates! Don't ML implementations have tail recursion elimination? Scheme implementations certainly do.

Paul Prescod

Andrew comments

You are right of course. Many implementation do indeed remove tail recursion. This means that where possible the interpreter "flattens out" a recursive structure into an iterative one. This can be demonstrated with a pair of functions:

fun count1 0 = 0
|   count1 n = 1 + count1(n-1);

fun count2 n = let
  fun c a 0 = a
  |   c a n = c (1+a) (n-1)
in c 0 n end;
Calling count1 1000000 requires ML to increase the heap and whereas count2 1000000 doesn't. The second call is completed substantially faster.

The calculations (1+..) is performed "on the way down" for count1 but is performs "on the way up" for count2.