# Lec04 - type answer = Yes | No | Maybe let x answer = Yes type optnum = Blank | Filled of int Blank Filled(3110 type intlist = Nil | Cons of(int

This preview shows pages 1–3. Sign up to view the full content.

type answer = Yes | No | Maybe let x: answer = Yes type optnum = Blank | Filled of int Blank Filled(3110) type intlist = Nil | Cons of (int * intlist) Cons(1, Cons(2, Nil)) let list1 = Nil (* the empty list: []*) let list2 = Cons(1,Nil) (* the list containing just 1: [1] *) let list3 = Cons(2,Cons(1,Nil)) (* the list [2;1] *) let list4 = Cons(2,list2) (* also the list [2;1] *) (* the list [1;2;3;4;5] *) let list5 = Cons(1,Cons(2,Cons(3,Cons(4,Cons(5,Nil))))) (* the list [6;7;8;9;10] *) let list6 = Cons(6,Cons(7,Cons(8,Cons(9,Cons(10,Nil))))) (* Returns the length of lst *) let rec length(lst: intlist): int = match lst with Nil -> 0 | Cons(h,t) -> length(t) + 1 (* test to see if the list is empty *) let is_empty(xs:intlist):bool = match xs with Nil -> true | Cons(_,_) -> false (* Notice that the match expressions for lists all have the same * form -- a case for the empty list (Nil) and a case for a Cons. * Also notice that for most functions, the Cons case involves a * recursive function call. *) (* Return the sum of the elements in the list *) let rec sum(xs:intlist):int = match xs with Nil -> 0 | Cons(i,rest) -> i + sum(rest) (* Create a string representation of a list *) let rec toString(xs: intlist):string = match xs with Nil -> "" | Cons(i, Nil) -> string_of_int(i) | Cons(i, Cons(j, rest)) -> string_of_int(i) ^ "," ^ toString(Cons(j,rest)) (* Return the first element (if any) of the list *) let head(is: intlist):int = match is with Nil -> raise(Failure "empty list!") | Cons(i,tl) -> i

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
(* Return the rest of the list after the first element *) let tail(is: intlist):intlist = match is with Nil -> raise(Failure "empty list!") | Cons(i,tl) -> tl (* Return the last element of the list (if any) *) let rec last(is: intlist):int = match is with Nil -> raise(Failure "empty list!") | Cons(i,Nil) -> i | Cons(i,tl) -> last(tl) (* Return the ith element of the list *) let rec nth ((is: intlist), (i:int)):int =
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 10/25/2009 for the course PHYS 2214 at Cornell University (Engineering School).

### Page1 / 5

Lec04 - type answer = Yes | No | Maybe let x answer = Yes type optnum = Blank | Filled of int Blank Filled(3110 type intlist = Nil | Cons of(int

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online