Chapter 4Standard ML

Declarations: val, fun, let, local

Bind names to values and functions

Concept

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).

Practice — score 100% to advance
Multiple choice
Q1
What does val x = 5; do?
Q2
What does fun declare?
Q3
In let val x = 1 in x + 1 end, what is the value?
Q4
What does 'shadowing' mean?
Q5
Per Def 1.4, what delimits the scope of a local declaration?
Q6
In let val x = 2 in (let val x = 3 in x end) + x end, what is the value?
Order the steps
Arrange these proof steps in the correct order using the arrows.
1
let val x = 20 in x + 1 end
2
Outer: val x = 10
3
Result: x + 10 (still uses outer x = 10)
4
Total: 10 + 21 = 31
Loading…