Declarations: val, fun, let, local
Bind names to values and functions
A declaration introduces a new name and binds it to a value. SML has three main forms.
1. val — value declaration. Binds a name to a single value.val pi = 3.1415;val msg = "hello";
2. fun — function declaration. Binds a name to a function. The parameters are bound only inside the function body.fun square (x: real) = x * x;fun double x = x + x;
You can also bind a function value via val:val inc = fn x => x + 1;
3. let ... in ... end — local declaration. Binds names that exist only between in and end.
val x = 10;
val y = let val x = 5 in x * 2 end;
(* x is still 10 here; y is 10 *)Def 1.4 (slides p.201) says: a local declaration uses let to bind variables in its scope (delineated by in and end). Local declarations can shadow existing names — the inner binding takes over until the scope ends.
Scope rule: an identifier is visible from its declaration until the end of the smallest enclosing let ... end (or the end of the file, for top-level declarations).
val x = 5; do?fun declare?let val x = 1 in x + 1 end, what is the value?let val x = 2 in (let val x = 3 in x end) + x end, what is the value?