HeapUnderStop
HeapUnderStop

Reputation: 398

Using the "of " keyword in OCaml

What does the of keyword do in these definition of lazylist and a function using the type? Is it just a constructor which defines the type of Cons, so that it takes a unit and computes a llist, or is there more to consider?

type 'a llist = Cons of 'a  * (unit -> 'a llist)

let rec lnat i = Cons (i, (fun () -> lnat (i + 1)))

(The lnat-function takes an int and constructs a list of all natural numbers, starting from that input int).

Upvotes: 3

Views: 1985

Answers (1)

Lhooq
Lhooq

Reputation: 4441

The of is just a way of saying "this algebraic datatype constructor is composed of ..."

But from the rest of your question, it doesn't seem you understand really well what algebraic datatypes and functions are.

Is it just a constructor which defines the type of Cons, so that it takes a unit and computes a llist

Well, no, Cons doesn't take a unit and computes a llist. Rather, Cons is composed of a pair of 'a and a function of type unit -> 'a llist.

Cons is what we would call a lazy list because it is not constructed unless you traverse it. This is a deferred computation.

The lnat-function takes an int and constructs a list of all natural numbers, starting from that input int

Once again, no. lnat takes an int and returns a new Cons containing this int as the first member of its pair and a function from unit to lnat (i+1).

This means that lnat is an infinitely recursive function constructing all the naturals from i to infinity but only if you explicitely explore Cons.

Example:

lnat 0 > Cons (0, (fun () -> lnat 1))

lnat 1 being behind a fun (), its value is not computed allowing your program to not run infinitely.

Upvotes: 6

Related Questions