Refnum

Stephen Weeks MLton@sourcelight.com
Wed, 19 Sep 2001 22:42:43 -0700


Henry pointed out that with my new signature, you don't even need refs, provided
you are willing to store the count along with the ref.  Code below.  I'm still
thinking about how to implement your original signature in SML, but I'm not
optimistic.

structure Refnum:
   sig
      val refnum: unit -> 'a ref -> int
   end =
   struct
      val count: int ref = ref 0

      fun 'a refnum () =
	 let
	    val rs: (int * 'a ref) list ref = ref []
	 in
	    fn (r: 'a ref) =>
	    let
	       fun loop l : int =
		  case l of
		     [] =>
			let
			   val n = !count + 1
			in
			   count := n
			   ; rs := (n, r) :: !rs
			   ; n
			end
		   | (n, r') :: l =>
			if r = r'
			   then n
			else loop l
	    in
	       loop (!rs)
	    end
	 end
   end