[ Reade, Ch. 3 ]
Informally: for all types T , there is a list of objects of type T :
[a1 , . . . , an ]
Not random access, but access from the left end (like a stack, with top
Lists are formed with two constructors
9. Streams (Infinite lists)
[A&S, 1st ed. 3.4; 2nd ed. 3.5]
To implement streams or infinite lists in SML, we must simulate
The idea is to code or store unevaluated expressions as functions.
To delay evaluation of E : , store it as
7. Higher Order Operations on Lists
[ Reade 3.4 ]
(1) To double the values of a list of integers:
e.g. double list [3, 1, 4] = [6, 2, 8].
Def. by list recursion:
fun double list (a:x) = (2 a):(double list x)
| double list [ ] = [ ];
5. Lazy and Eager Evaluation
[ Reade Chs. 8, 9 ]
Order of evaluation of an expression usually makes no difference; e.g.:
let val x = 5 + (4 2)
in (4 x) + (3 - x)
If evaluate expr. after substitution: lazy.
If not: eager or strict.
Example 1. Factorial function:
fun fact n = if n = 0
else n * fact (n-1);
val fact = fn : int int
Alt.: using pattern matching (p.m.)
fun fact 0 = 1
| fact n = n * fact (n-1);
Note. This defines a fun
8. Concrete Data Types
[ Reade ch. 5 ]
We can define new types (data types) with constructors.
(Dont need selectors!)
Then we can define functions on those data types
recursion on construction of data types or
structural recursion on data types or
[Reade ch. 2]
fun I x = x;
Q. What is its type?
A. I : , for any type .
Introduce type variables , , , . . .
(Represented in ASCII by a, b, c, . . . .)
We get polymorphic types.
fun I x = x
11. Computability and Continuity
Continuity becomes an important consideration for computing on
infinite data such as streams.
An initial segment of a stream s = ha1 , a2 , . . .i is an initial (finite)
tuple of s: ha1 , . . . , an i (f
12. Two Paradigms of Programming Languages:
Imperative and Functional
Interpreting an Imperative Language in SML
An imperative programming language (Pascal, C, Java, . . . ) has, as
its basic command, the assignment X := E.
A program in such a langua
10. More Stream Operations
Example: Stream of primes
As preparation, we define the integer square root function:
fun sqrt 0 = 0
| sqrt n = let val k = sqrt (n 1) in
if (k + 1) (k + 1) > n
else k + 1
. . . and the prime number predicate: