#light module Eleven type day = Mon | Tues | Wed | Thurs | Fri | Sat | Sun // p. 166 let isWeekDay x = not (x = Sat || x = Sun) printfn "%A" (isWeekDay Mon) printfn "%A" (isWeekDay Sat) type flip = Heads | Tails let isHeads x = (x = Heads) printfn "%A" (isHeads Tails) let isWeekday1 = function // p. 167 | Sat -> false | Sun -> false | _ -> true type exint = Value of int | PlusInf | MinusInf printfn "%A" (PlusInf) // p. 168 printfn "%A" (Value) printfn "%A" (Value 3) let x = Value 5 let (Value y) = x printfn "%A" (y) let s = match x with // p. 169 | PlusInf -> "infinity" | MinusInf -> "-infinity" | Value y -> y.ToString() printfn "%A" (s) let square = function | PlusInf -> PlusInf | MinusInf -> MinusInf | (Value x) -> Value (x*x) printfn "%A" (square MinusInf) printfn "%A" (square (Value 3)) type 'a option = NONE | SOME of 'a // predefined let optdiv a b = if b=0 then NONE else SOME (a/b) // p. 170 printfn "%A" (optdiv 7 2) printfn "%A" (optdiv 7 0) type 'x bunch = One of 'x | Group of 'x list let size = function // p. 171 | (One _) -> 1 | (Group x) -> List.length x printfn "%A" (size (One 1.0)) printfn "%A" (size (Group [true;false])) let sum = function | (One x) -> x | (Group xlist) -> List.fold_right (+) xlist 0 printfn "%A" (sum (One 5)) printfn "%A" (sum (Group [1;2;3])) type intlist = INTNIL | INTCONS of int*intlist let rec intlistlength = function | INTNIL -> 0 | INTCONS(_,tail) -> 1+(intlistlength tail) printfn "%A" (intlistlength (INTCONS (1, INTCONS(2, INTNIL)))) type 'element mylist = NIL | CONS of 'element * 'element mylist let rec myListLength = function // p. 173 | NIL -> 0 | CONS(_,tail) -> 1+myListLength(tail) printfn "%A" (myListLength (CONS (1, CONS (2,NIL)))) let rec myfoldr = function | (f, c, NIL) -> c | (f, c, (CONS (a,b))) -> f(a, myfoldr(f, c, b)) printfn "%A" (myfoldr((fun(a,b) -> a+b), 0, NIL)) printfn "%A" (myfoldr((fun(a,b) -> a+b), 0, (CONS (1, CONS (2, NIL))))) type 'data tree = // p. 174 Empty | Node of 'data tree * 'data * 'data tree let treeEmpty = Empty // p. 175 let tree2 = Node(Empty,2,Empty) let tree123 = Node(Node(Empty,1,Empty), 2, Node(Empty,3,Empty)) let rec incall = function | Empty -> Empty | Node(x,y,z) -> Node(incall x, y+1, incall z) printfn "%A" (incall tree123) let rec sumall = function | Empty -> 0 | Node(x,y,z) -> sumall x + y + sumall z printfn "%A" (sumall tree123) let rec listall = function | Empty -> [] | Node(x,y,z) -> listall x @ y :: listall z printfn "%A" (listall tree123) let rec isintree = function | (x, Empty) -> false | (x, (Node(left,y,right))) -> x=y || isintree(x,left) || isintree(x, right) printfn "%A" (isintree(4, tree123)) printfn "%A" (isintree(3, tree123))