[MLton] Optional Arguments and FRU

Vesa Karvonen vesa.karvonen@cs.helsinki.fi
Tue, 23 Aug 2005 16:03:09 +0300


The Optional Arguments (OA) technique presented on the page

  http://mlton.org/OptionalArguments

is basically a combination of FRU and CPS. With the recent updates to
the FRU technique, I think that it might be a good idea to revisit the
OA page. Using latest FRU techniques, OA could be done something like
this:

  (* The original function *)
  fun f x {a, b, c} = a * (real c) + b * (real x)

  (* The defaults *)
  val defs = {a = 0.0, b = 0.0, c = 0}

  (* A function taking optional arguments *)
  fun f' x upds = f x (foldl op|< defs upds)

Now f' can be used like this:

   val x = f' 1 []
   val y = f' 1 [set#b 1.0]
   val z = f' 1 [set#a 1.0, set#c 2, set#b 1.0]

assuming that `set' is a FRU setter for the argument record:

  fun set f =
      let
         fun t2r (v1, v2, v3) = {a = v1, b = v2, c = v3}
         fun r2t {a = v1, b = v2, c = v3} = (v1, v2, v3)
      in
         wrapSet (set3, t2r, t2r, r2t) f
      end

I think that this compares quite favorably to the technique currently
presented on the OA page.

The FRU technique also allows fairly convenient syntax for calling
the original function given just the defaults. For example:

   val x = f 1 defs
   val y = f 1 o set#b 1.0 |< defs
   val z = f 1 o set#a 1.0 o set#c 2 o set#b 1.0 |< defs

-Vesa Karvonen