fib, new primitives, and useless analysis

Stephen Weeks MLton@research.nj.nec.com
Wed, 21 Jun 2000 14:17:47 -0700 (PDT)


Here's an amusing consequence on the compilation of fib of the
interaction of the new primitives and useless analysis.

Suppose fib is defined as

val rec fib: int -> int =
   fn 0 => 0
    | 1 => 1
    | n => fib(n - 1) + fib(n - 2)

Further suppose that there is a single outer call to fib that ignores
the result.  MLton is not smart enough to prove the termination of
fib, so it can not eliminate the call to fib entirely.  MLton does,
however, turn fib into the following.

val rec fib: int -> unit =
   fn 0 => ()
    | 1 => ()
    | n => (fib(n - 1); fib(n - 2))

The reason that this surprised me is that I thought that MLton would
think that the result of fib is necessary in order to do the +.  But
of course you only need to do the + if the result of fib is necessary,
so the least fixed-point in the useless analysis does the right thing,
which is to conclude that the result of fib and the + are unnecessary.
Neat!