Escolar Documentos
Profissional Documentos
Cultura Documentos
Types
Types in ML
[ Reade, §1.3 ]
We want to generate:
• Type expressions T, T ′ , . . .
• Expressions E : T (E is an expression of type T )
(Type formation)
T1 is type . . . Tn is type (n ≥ 2)
T1 × · · · × Tn is type
(Tuples)
E1 : T1 E2 : T2 . . . En : Tn
(E1 , E2 , . . . , En ) : T1 × T2 × . . . × Tn
4
(Type formation)
T1 is type T2 is type
T1 → T2 is type
(Application)
F : T1 → T2 E : T1
F E : T2
(more later)
iv. Conditionals
E1 : bool E2 : T E3 : T
if E1 then E2 else E3 : T
Predefined Functions in ML
[ Reade, p.16, Table 1.1 ]
Examples:
+
−
∗ : int × int → int (infix)
div
mod
∼ : int → int
≥
≤
: int × int → bool (infix)
>
<
andalso
: bool × bool → bool (infix)
orelse
even
: int → bool
odd
Important: = : ?
Function Definitions
– 1 + 1;
> val it = 2 : int
(Note: This expression is treated as an implicit declaration of the pre-
defined variable ‘it’. So the value of the last top level expression evaluated
can be referred to by ‘it’.)
– 1 + (1.0);
! Type clash . . .
Note: No type coercion!
– fun double x = 2 ∗ x;
> val double = fn : int → int
– double 3;
> val it = 6 : int
– double true;
! Type clash . . .
– fun suc n = n + 1;
val suc = fn : int → int
– suc 3;
> val it = 4 : int
7
– triple 3;
! Unbound value identifier: triple
– fun plus(m, n) = m + n;
> val plus = fn : int ∗ int → int
Note: Overloaded operators like ‘+’ default to int!
Syntactic Errors
Curried Functions
– fun plus c m n = m + n;
> val plus c = fn : int → int → int
Notes:
1. For m, n: int,
plus c m : int → int and
plus c m n = plus(m, n) = m+n.
8
Conventions:
Note: In both cases, scope of local function is restricted to end of fun def.
Notes: