Expanded Recursive Diagrams OCAML rapid tour, day 2

Slides:



Advertisements
Similar presentations
Higher-Order Functions and Loops c. Kathi Fisler,
Advertisements

Modern Programming Languages, 2nd ed.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Programovací jazyky F# a OCaml Chapter 3. Composing primitive types into data.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
CSE341: Programming Languages Lecture 4 Records (“each of”), Datatypes (“one of”), Case Expressions Dan Grossman Fall 2011.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Introduction to ML Last time: Basics: integers, Booleans, tuples,... simple functions introduction to data types This time, we continue writing an evaluator.
Patterns in OCaml functions. Formal vs. actual parameters Here's a function definition (in C): –int add (int x, int y) { return x + y; } –x and y are.
CSE 341 Programming Languages Racket Datatype Style Programming Zach Tatlock Spring 2014.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CS 152: Programming Language Paradigms February 12 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
ML: a quasi-functional language with strong typing
Class 11: Two-argument recursion
Short Circuits Design Recipe Redux Structures
Functions and patterns
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Winter 2013.
Section 2 – CSE341 Patrick Larson, Spring 2013.
review, let and lambda, trees?, tree-recursion?, OCAML intro
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2017.
32: Games 3 Functional Data
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2013.
review combinatorics bignum OCAML rapid tour, day 3
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Zach Tatlock Winter 2018.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2017.
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2016.
Section 2 – CSE341 Konstantin Weitz.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2018.
Nicholas Shahan Spring 2016
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Winter 2013.
The Metacircular Evaluator
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2013.
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Winter 2018.
CSE 341 Section 2 Winter 2018 Adapted from slides by Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE 341 PL Section 2 Justin Harjanto.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Autumn 2017.
Type & Typeclass Syntax in function
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2017.
CSE 341 Section 2 Nick Mooney Spring 2017
6.001 SICP Variations on a Scheme
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2016.
Announcements Quiz 5 HW6 due October 23
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2016.
Functions and patterns
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Doug Woos Winter 2018.
Functions and patterns
CSE 341 Lecture 2 lists and tuples; more functions; mutable state
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Spring 2019.
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
CSE341: Programming Languages Lecture 5 More Datatypes and Pattern-Matching Dan Grossman Spring 2019.
CS 5010 Program Design Paradigms “Bootcamp” Lesson 4.1
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
Review Previously User-defined data types: records, variants
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Spring 2019.
Presentation transcript:

Expanded Recursive Diagrams OCAML rapid tour, day 2 Class 18 Expanded Recursive Diagrams OCAML rapid tour, day 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.

Expanded recursive diagrams

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

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

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

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.

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"

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

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

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

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

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!

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

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

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

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

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

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?

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

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

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;;

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

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”

“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

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>

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

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

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 »