[MLton-user] Wish for a standard sum type

Vesa Karvonen vesa.karvonen@cs.helsinki.fi
Fri, 2 Jun 2006 11:42:21 +0300


Quoting Jesper Louis Andersen <jlouis@mongers.org>:
> signature ALTERNATE =

I would probably prefer an abbreviation like Alt :> ALT.  (I
would also prefer an abbreviation for Option as well.)  This
is a very general and stable module and, IMO, deserves a short
name.

> sig
>     type ('a, 'b) t

I would definitely expose the constructors to allow ad hoc
pattern matching.

>     exception SumMismatchException

I think that in this case an exception named after the module
name would be appropriate as this is likely to be the only
exception that one would ever have in this module.

>     val inl : 'a -> ('a, 'b) t
>     val inr : 'b -> ('a, 'b) t
> 
>     val isl : ('a, 'b) t -> bool
>     val isr : ('a, 'b) t -> bool
> 
>     val outl : ('a, 'b) t -> 'a
>     val outr : ('a, 'b) t -> 'b

I would also have:

      val out : ('a, 'a) t -> 'a

>     val alternate : ('a -> 'c) * ('b -> 'c) -> ('a, 'b) t -> 'c
>     val parallel  : ('a -> 'c) * ('b -> 'd) -> ('a, 'b) t -> ('c, 'd) t

I would call this "map" inside the module, and would also
bind it at the top level as "pipe" (after the symbol |,
which can be thought of as the symbol of the associated
type constructor).

One occasionally useful function that I didn't spot in
the Alice ML module:

  val mirror : ('a, 'b) t -> ('b, 'a) t

One could also call it "swap".

> [...] His good
> reason to reject FST and SND was that fst and snd are defined on A * B
> (the product composition on types) rather than A + B (the sum
> composition), technical or not, heh.

Yes.  I prefer to have fst and snd bound on the top level to #1 and #2
on pairs.  I find them very useful.

> It _is_ useable in other cases. I view it as an data-equivalent of an
> if..then..else.. control-construct. Sometimes there are 2 outcomes,
> which are not easily writeable with a if-then-else block. In that case,
> it might be to your advantage to pass it via the data rather than via
> control.

Yes.  That is basically how I used it in a (proof-of-concept) Format
module, which I constructed as the sum of Printf and Scanf modules.
The FRU (Functional Record Update) technique also uses it.

(You can see both uses it in my (temporary) "Fold-sandbox" at
   http://www.cs.helsinki.fi/u/vkarvone/fold/
N.B. The basic.sml file there just contains ad hoc copy-and-paste
from my utility libs.  I didn't want the code there to depend on my
libs (where I already have an Either module).)

-Vesa Karvonen