[MLton] handling a variable number of arguments in SML

Stephen Weeks MLton@mlton.org
Tue, 23 Aug 2005 14:11:42 -0700


Before it possibly disappears, I thought it would be instructive to
distill the essence of the technique that the (current)
OptionalArguments page uses to handle a variable number of arguments.
Below is the simplest version I could come up with, which shows how to
define a function "f" that takes a variable number of "a" arguments,
and when it receives the end of arguments marker, "$", returns the
number of "a"s it received.

----------------------------------------------------------------------

signature S =
   sig
      type 'a v
      type 'a u = 'a v -> 'a

      val $ : int v
      val f: 'a u
      val a: 'a u v
   end

functor F (S: S) =
   struct
      open S

      fun p i = print (concat [Int.toString i, "\n"])
      val () = p (f $)
      val () = p (f a $)
      val () = p (f a a $)
      val () = p (f a a a $)
      val () = p (f a a a a $)
      val () = p (f a a a a a $)
   end
  
structure S: S =
   struct
      type 'a v = int -> 'a
      type 'a u = 'a v -> 'a

      fun $ i = i
      fun f g = g 0
      fun a i g = g (i + 1)
   end

structure Z = F (S)