Definition:
In typical languages like C, a variable declaration creates a binding between an identifier and a storage location. The declaration may or may not also initialize the variable, i.e. bind the location to a value.
The most fundamental variety of command is the assignment command.
An assignment changes the value that is bound to a storage location.
Conceptually not1 and not2 both have the same mapping type, i.e. boolean -> boolean.type boolean = {false, true};const not1: array [boolean] of boolean := [true, false];
function not2 (x: boolean): boolean;
begin
if x then return false else return true;
end;
In ML the syntax for constant declarations is more regular: you can write
Here the keyword val means this is a direct binding of an identifier to a valueval not2 = fn (x: bool) => if x then false else true;
The right-hand side of the = sign is an anonymous function: an expression
that denotes a function. In ML any expression, denoting a value of any
type, can appear in a val declaration.
In most programming languages, variables are updatable. This means that the actual value of a variable is a memory address. Assignment commands then change the value stored at this address.
Definition: In a functional language variables are not updatable. An imperative language does have updatable variables.
Since they do not have updatable variables, functional languages do not have commands. ML is a functional language.
In an imperative language like Pascal, a const declaration
is the same thing as a val declaration in a functional language
like ML.
In other words, an environment is a set of bindings where each binding is an ordered pair <name, value>. The simplest way to implement an environment is to use a list of pairs. This is adequate theoretically but for practical use a more efficient data structure must be used.
Environments are ubiquitous in PLs. A PL implementation must keep
track of environments both at compile-time and at run-time.
The syntax (w, n) :: env is ML pattern-matching for a list whose head is the ordered pair (i.e. tuple)(w, n) and whose tail is env.exception Free_Variable
fun lookup v [] = raise Free_Variable
| lookup v ((w, n) :: env) = if v = w then n else lookup v env
The next function evaluates an arithmetic expression according to an environment:
Be sure that you understand the ML code above completely before you start writing code for the second project.fun eval (Lit n) env = n
| eval (Var v) env = lookup v env
| eval (Plus (exp1,exp2) ) env = (eval exp1 env)+(eval exp2 env)
| eval (Times (exp1,exp2) ) env = (eval exp1 env)*(eval exp2 env)- val b1 = ("x", 2); - val b2 = ("y", 3);
- eval (Times((Var "x"), (Var "y"))) [b1,b2]; val it = 6 : int