Commit 62bbec50 authored by James R. Wilcox's avatar James R. Wilcox
Browse files

lec09 code

parent 3fe42bc3
type my_variant =
| Name of string
| Height of int
let a = Name("james")
let b = Height(75)
let l = [a; b]
(* not allowed: ["james"; 75] *)
let my_variant_message (v: my_variant): string =
match v with
| Name s -> "hello " ^ s (* s is only available in this branch *)
| Height i -> "you must be this tall to ride: " ^ Int.to_string i (* could not refer to s here*)
(* there is the built-in option type, which is defined sort of like this: *)
type my_int_option =
| MyNone
| MySome of int
let c = MyNone
let d = MySome(17)
(* no need for Option.is_some and Option.get any more. ocaml programmers use match instead *)
let f (mio: my_int_option): string =
(* on hw2, we would have written this
if Option.is_some mio
then Int.to_string (Option.get mio)
else "no integer found!"
*)
match mio with
| MyNone -> "no integer found!"
| MySome i -> Int.to_string i
(*
option is defined roughly like
type option =
| None
| Some of ... something
*)
let f (io : int option): string =
match io with
| None -> "foo"
| Some i -> Int.to_string i
type silly =
| Pizza of string * string * string
| Croissant of int
| Salad
let a = Pizza("sauce", "cheese", "vegan sausage")
let _ =
match a with
| Pizza(topping1, topping2, topping3) -> topping1 ^ " " ^ topping2 ^ " " ^ topping3 ^ " pizza"
| Croissant i -> Int.to_string i
| Salad -> "iceberg lettuce"
type my_int_list =
| Nil
| Cons of int * my_int_list
let rec mysum (l: my_int_list): int =
match l with
| Nil -> (* base case *) 0
| Cons(head, tail) ->
(* recursive case: have access to "mysum tail" *)
head + mysum tail
let x = Cons(1, Cons(2, Cons(3, Nil)))
let y = mysum(x)
(* built in lists are almost like:
type list =
| []
| :: of (element type) * list
*)
let rec sum (l: int list): int =
(*
if l = []
then 0
else List.hd l + sum (List.tl l)
*)
match l with
| [] -> 0
| head :: tail ->
head + sum tail
(* sum tail *)
let z = [1; 2; 3]
let w = sum z
type expr =
| Constant of int
| Plus of expr * expr
| Mult of expr * expr
let e1 = Constant(3)
let e2 = Plus(Constant(1), Constant(2))
let e3 = Plus(e2, Constant(17))
let rec eval (e: expr): int =
match e with
| Constant(n) -> n
| Plus(e1, e2) ->
eval e1 + eval e2
| Mult(e1, e2) ->
eval e1 * eval e2
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment