unsafe code in mlton

Stephen Weeks MLton@sourcelight.com
Wed, 19 Sep 2001 14:40:57 -0700


> For diagnostic purposes, I've written some unsafe NJ code that
> enables me to implement a function of type 'a ref -> int:
...
> Any idea how I might do something similar in MLton?
> Unsafe.cast would probably be enough...

Here is a slightly different signature that can be implemented in a type-safe
way using exceptions.  Is that enough?

structure Refnum:
   sig
      val refnum: unit -> 'a ref -> int
   end =
   struct
      val count: int ref = ref 0
      val exns: exn list ref = ref []

      fun 'a refnum () =
	 let
	    exception E of 'a ref
	 in
	    fn (r: 'a ref) =>
	    let
	       fun loop (l, i) =
		  case l of
		     [] =>
			let
			   val n = !count + 1
			in
			   count := n
			   ; exns := E r :: !exns
			   ; n
			end
		   | E r' :: l =>
			if r = r'
			   then i
			else loop (l, i - 1)
		   | _ :: l => loop (l, i - 1)
	    in
	       loop (!exns, !count)
	    end
	 end
   end