Search code examples
smlsmlnj

Function that takes type unit


I'm trying to create a function that has the type:

unit -> (int list * int list * int list)

But I was wondering, unit is an empty type (has no value), so how would it be possible to do something with it and return 3 int lists?

Thanks


Solution

  • The type unit is not empty.
    It has one value which is spelled () and is usually called "unit", like its type.
    (One meaning of the word "unit" is "a single thing".)

    Example:

    - ();
    val it = () : unit
    - val you_knit = ();
    val you_knit = () : unit
    
    - fun foo () = ([1], [2], [3]);
    val foo = fn : unit -> int list * int list * int list
    - foo ();
    val it = ([1],[2],[3]) : int list * int list * int list
    - foo you_knit;
    val it = ([1],[2],[3]) : int list * int list * int list
    

    (Note that () is not an empty parameter list; ML doesn't have parameter lists.)

    Strictly speaking, the above definition pattern-matches on the value ().
    Without pattern matching, it could look like this:

    - fun bar (x : unit) = ([1], [2], [3]);
    val bar = fn : unit -> int list * int list * int list
    - bar ();
    val it = ([1],[2],[3]) : int list * int list * int list