[MLton-user] 'a ref for C programmers: a primer

Matthew Fluet fluet at tti-c.org
Mon Feb 12 11:04:16 PST 2007


Wesley W. Terpstra wrote:
> As a former C programmer, I've always been confused by 'a ref in SML.
> I wanted to state how I've come to think about them for anyone else who 
> is confused.

I agree with Tom, that trying to explain the meaning of an SML program 
in terms of 'pointers' probably confuses the issue more than it helps. 
Indeed, for something like MLton, the whole point is that the meaning of 
an SML program is well-defined without needing to invoke any particular 
representation or runtime requirements.

> MLton may also be able to save the binding pointer. However, this 
> savings will never place the mutable pointer on the stack, as a 
> reference from the heap to the mutable pointer could outlive the current 
> stack frame. So, when you have a variable like 'x' above, you are pretty 
> much guaranteed that there is at least one level of indirection going on.

This isn't quite true.  MLton will eliminate a reference cell that 
doesn't outlive its scope.  A common idiom that is picked up is the 
following:

fun mapAndLength f l =
   let val r = ref 0
       val l' = map (fn x => (r := !r + 1; f x) l
   in
     (l', !r)
   end

The use of the reference is completely local to the function (after 
inlining the code for map) and MLton will eliminate heap allocated 
reference cell in favor of a stack local integer holding the length.





More information about the MLton-user mailing list