Tuples and Lists

Posted by Beetle B. on Sat 30 July 2016

Tuples

Syntax

(e1, e2, ..., en)

Note that the length of a tuple is known in advance.

Type Checking

ei will have type ti (the types need not be the same). The type of the expression will be t1*t2*...*tn.

Note that ei could itself be a tuple, so we can nest to our heart’s content.

Evaluation

If ei evaluates to vi, then the value is the tuple (v1, v2, ..., vn)

Accessing Values

To access the first value, use #1 e and so on.

Relationship to Records

Tuples are just syntactic sugar for records.

Lists

Lists do not need to predefine their length. However, all of its elements must be of the same type.

Empty List

The empty list is []. Its type is 'a list, pronounced alpha list. It represents any type.

So if you have a function that returns a list of type t, it is always safe to return [].

List of Lists

If you have a list of list of int, then its type is:

int list list

If you have a list of tuples of ints, then its type is:

(int*int*int) list“

Nonempty List

Syntax

Explicit:

[e1, e2, ..., e3]

Constructed:

e1::e2

Type Checking

Explicit:

If all the en are of type t, then the type of the list is t list.

Constructed:

e1 is of type t. Then e2 must be of type t list.

null

null evaluates to true for empty lists. false otherwise.

Head and Tail

hd returns the first element of the list, or throws an exception for empty lists.

tl returns the list starting from the second element. It raises an exception if empty.

Concatenating Two Lists

[1,2,3] @ [4,5]

Using case

As is described later on, it is better to use case than hd, tl and null.