Lecture 03
Tuples, Lists
Programming Languages
UW CSE 341 - Spring 2023
OCaml Carefully So Far
Compound Data Types
General Design Principle
Whenever we design a new type t we need two things:
Example:
Build t1*t2*...*tn->t with function bindings, use with function calls
Example:
Build bool with true and false, use with if e1 then e2 else e3
More systematic approach to defining / understanding programming languages!
Pairs (2-tuples) : Build
Syntax: (e1, e2) where e1 and e2 are expressions
Type Checking
Evaluation
PAIR
The Star of the Show
Nested Pairs
Pairs can be nested
((1,4),(2,(true,3)) : (int * int) * (int * (bool * int))
Pairs (2-tuples) : Use
Syntax: fst e and snd e
Type Checking
Evaluation
Fib alert: fst and snd are actually library functions, but we will pretend they are “built in” for another week or so.
Tuples : Build
Syntax: (e1, …, eN)
Type Checking
Evaluation
Tuples : Use
Nested pairs vs. tuples
let x = (5,7,9)
(* x : int*int*int *)
let seven = snd3 x
(* snd x doesn’t type-check *)
let x = (5,(7,9))
(* x : int*(int*int) *)
let seven = fst (snd x)
let pr = snd x
(* snd3 x doesn’t
type-check *)
Compound Data Types
Lists : Build
Syntax: [e1; …; eN]
Type Checking
Evaluation
Lists of values are values.
Elements separated by semicolons “ ; ” ⚠️
Get very weird error messages otherwise ⚠️
All same type t
Lists : Build
Syntax: [e1; …; eN]
Type Checking
Evaluation
New kind of type!
t list
Another type constructor (list) for making the type of lists whose elements have type t.
Examples:
bool list int list
(int * (int * int)) list
int list list
Lists : Build
Syntax: [e1; …; eN]
Type Checking
Evaluation
N can be zero!
[] is the empty list for any type.
[]
So if all zero elements of [] have type t, then [] has type t list
Lists : Build with “cons” (::)
Syntax: e1 :: e2
Type Checking
Evaluation
“Create (construct) a list with one more element at the front”
Two ways to build?
Lists : Use
Lists : Use -- Test for empty
Syntax: e = []
Type Checking
Evaluation
Lists : Use -- Get the first element
Syntax: List.hd e
Type Checking
Evaluation
Alternate definition:
List.hd has type ‘a list -> ‘a
Lists : Use -- Get the rest (everything after first)
Syntax: List.tl e
Type Checking
Evaluation
Alternate definition:
List.tl has type ‘a list -> ‘a list
Recursion again!
Lists of tuples