Search code examples
functional-programmingsml

Declare multiple variable bindings in one line in SML


Is it possible to declare multiple variable bindings in one line in SML? For example, I have the following:

let
    val m1 = [1]
    val m2 = [2]
    val m3 = [3]
in
    {...}
end

I would like to condense this down to something like

let
    val m1 = [1], m2 = [2], m3 = [3]
in
    {...}
end

This syntax doesn't work, but is there a way to declare multiple variable bindings in one line like this?


Solution

  • Here are two ways:

    - let val x = 1 val y = 5 in x + y end;
    val it = 6 : int
    - let val x = 1 and y = 5 in x + y end;
    val it = 6 : int
    

    I personally find the slight abuse of and more readable.
    However, I think the "destructuring bind" method is more common than either of these, since it's also more generally useful.

    - let val (x, y) = (1,5) in x + y end;
    val it = 6 : int
    - fun f x = (x, x + 2, x + 3);
    val f = fn : int -> int * int * int
    - let val (x, y, z) = f 3 in x + z end;
    val it = 9 : int