Presentation is loading. Please wait.

Presentation is loading. Please wait.

Expanded Recursive Diagrams OCAML rapid tour, day 2

Similar presentations


Presentation on theme: "Expanded Recursive Diagrams OCAML rapid tour, day 2"— Presentation transcript:

1 Expanded Recursive Diagrams OCAML rapid tour, day 2
Class 18 Expanded Recursive Diagrams OCAML rapid tour, day 2

2 Note This week's HW is in Racket; this week's Lab gives you a chance to play with Ocaml and make sure you've got it set up and working on your own computer. We'll just have to be bilingual for a little while The design recipe applies to Ocaml programs, too, with slight variations: Type signature is part of the code, not the comments Type-descriptions (like "a database is a list of 2-element string lists") are now mostly in code, not comments Exception: "A set is a list without repetitions": about contents, not structure check_expect is now spelled with an underscore, and it's not as fancy as the one in Racket.

3 Expanded recursive diagrams

4 A new part of the problem: from OI to RI
Example: fold OI: +, 0, (list 3 2 1) how do we get to the recursive input??? RI: +, ???, (list 2 1) RO: 6 just copy recursive output to overall output! OO: 6

5 A new part of the problem: from OI to RI
Example: fold OI: +, 0, (list 3 2 1) copy the proc; take "rest" of list; for "init", combine it with (first alod) using "proc" RI: +, 3, (list 2 1) RO: 6 just copy recursive output to overall output! OO: 6

6 OCaml tour continued: back to lecture 8, and length of a list

7 A minor difference between OCaml and Racket
In OCaml, there's no "define", only "let" and "let rec" let x = 5 <remainder of program> is like (let ((x 5)) (remainder of program)) i.e., the let-binding remains in force for everything below it.

8 Writing a recursive procedure
# let rec myLen (lst: 'a list):int = match lst with | [] -> 0 | hd::tl -> 1 + myLen tl;; match…with is the new "cond" | is used to indicate various cases -> is used to separate the case-selection from the associated value Some clever name-assignment goes on too let rec is used instead of "define"

9 Let's work up to that a little more slowly…

10 Review of types (and a few more)
Atomic types: int, float, bool, string, char Tuples: (3, “a”) : int * string. (4.0, ‘b’) : float * char Lists: [], ::, [ ; ; ] Parameterized type: int list, string list, etc. Generic: ‘a list

11 More types Variant types (more details later) type season = Fall | Winter | Spring | Summer type base = A | T | C | G type card = Clubs of int | Hearts of int | Spades of int | Diamonds of int type racket_value = | Number of int | Boolean of bool | String of string | Builtin of ??? | User_proc of (string list) * expression * (binding list) Things on the right ('constructors') must start with a capital Things on left (type-names) must start lowercase

12 Even more types Parameterized variant types:
type ‘a tree = | Leaf | Node of ‘a * ‘a tree * ‘a tree Records (which we will almost never use) another alternative to structs, but with no useful form for pattern matching; can also be thought of as “tuples with names for the parts”. type point_3d = {x : int; y : int; z : int} # let origin3 = ({x = 0; y = 0; z = 0} : point_3d) # origin.z # − : int = 0

13 Pattern matching Replaces the main “cond” in most procedures
A “match expression” looks like this: match <expr> with | pattern1 -> result1 | pattern2 -> result2 Allowable patterns: constants, identifiers, tuples of patterns, constructors with dummy arguments, wildcards Constructor example: Hearts n Matches Hearts 3 Temporarily makes n be 3 Can refer to n in the “result” expression! Combines “cond” and part-extraction and “let” all in one!

14 Pattern matching Allowable patterns: constants, identifiers, constructors with identifier arguments, wildcards Constant example: 14 Matches only the number 14 Wildcard example: Hearts _ Matches anything, but the matched thing has no name to let you use it Identifier examples: n (matches anything) Hearts r

15 Pattern matching idioms
match lst with | [] -> 0 | hd::tl -> hd + myfunc tail;; | hd::_ -> 2*hd;; match (s:season) with | Fall -> 68 | Winter -> 34 | Summer -> 85 | Spring -> 65

16 Pattern matching idioms: using the matched item as well as the pattern
match lst with | [] -> 0 | hd::tl -> hd + List.length lst;;

17 Pattern matching tuples
match pair with | (a, b) -> something involving a and b Serves as an easy way to tease apart a tuple and give names to all the pieces. | (true, b) -> something involving b | (_, a) -> 14 * a Another way to break into various cases

18 Pattern matching with conditions
match num with | n when n < 3 -> 11 | n -> 22

19 Imagine implementing Ocaml in Racket…types
You might represent each value as a list of two items: (list "int" 37) (list "string" "hello") (list "Cons" (list 1 2 3)) (list "Empty" empty) (list "Clubs" 4) ;; represents 4 of clubs Hmmm. Is the first item in our list the type of the item, or the constructor that was used to construct it?

20 Let's make it a list of THREE elements
(list "int list" "::" (list 1 2 3)) (list "int list", "[]" empty) (list "card" "Clubs" 3) (list "season" "Fall" <nothing>?) Now it's easy to see how "matching" could work: we say "if this card was constructed with the Club constructor, then produce this value; if it's a Heart then produce this

21 List recursion template
let rec proc (alod : ’a list) : ’b = match alod with | [] -> ... | hd :: tl -> ... hd ... proc tl ... QUIZ: use this to write “length”

22 Syntactic Sugar let rec proc: ’a list -> ’b = function | [] -> ... | hd :: tl -> ... hd ... proc tl … let rec length: ’a list -> int = function | [] -> 0 | _ :: tl -> 1 + length tl;;

23 Natural number recursion template
let rec proc (num: int) : ’b = match num with | 0 -> ... | n when (n > 0) -> ... num ... proc (n-1) ... | _ -> failwith “Proc: input isn’t a natural number” let rec proc: int -> ’b = function

24 Two-argument recursion template
let rec proc (n: int) (alod: ‘alist) = match (num, alod) with | 0, [] -> ... | 0, hd::tl -> ... | n, [] when (n > 0) -> .. n .. proc.. (n-1) | n, hd::tl when (n > 0) ->..n..proc..(n-1)..hd..tl.. | _,_ -> failwith “Proc: input isn’t a natural number”

25 “let”, expanded We’ve seen “let” (analogous to define) and “let rec” (allowing definition of recursive things) let … and allows definitions of multiple things, as in let x = 1 and y = 2 Also available in let…rec form. let...in analogous to Racket let-expression (creates temporary bindings)" # let in x + y;; -: int = 3

26 Ocaml functions We’ve seen a bunch of “infix” functions, like “+” (which takes two ints and returns an int) These functions are written between their arguments We, too, can define infix functions…but we won’t. We’ll only define “prefix” functions, whose name goes before the argument. # let add17 (num:int):int = num + 17;; # add17 1;; -:int = 18 General forms: let (<id>:<type>):<type> = <expr> usually on next line let rec (<id>:<type>):<type> = <expr>

27 Lambda Can add type annotations: fun <ident> -> <expr>
fun x –> x + 1 # (fun x -> x + 1) 2;; -: int = 3 Can add type annotations: fun (x:int) –> x + 1

28 let add17 = fun num -> num + 17
Syntactic sugar again In Racket, (define (f x)…) was really (define f (lambda (x) …)) In Ocaml, let add17 num = num + 17; is really let add17 = fun num -> num + 17

29 Multi-argument procedures
In Ocaml fun x y -> x + y + 1 looks like a 2-arg function. It’s not. Let’s see: # fun x y -> x + y + 1;; - : int -> int -> int = <fun> The truth: it’s really syntactic sugar for # fun x -> (fun y -> x + y + 1);; : int -> int -> int = <fun> Rewriting multi-arg functions as nested one-arg functions is called « Currying »


Download ppt "Expanded Recursive Diagrams OCAML rapid tour, day 2"

Similar presentations


Ads by Google