Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types.

Slides:



Advertisements
Similar presentations
Formal Models of Computation Part II The Logic Model
Advertisements

More ML Compiling Techniques David Walker. Today More data structures lists More functions More modules.
Haskell Lets review some of the Haskell concepts you have been learning on your own. The answers are included, but try it yourself first.
Modern Programming Languages, 2nd ed.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  Elements may appear more than once.
A First Look at ML.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Introduction to OCaml Slides prepared by Matt Gruskin Some material borrowed from the CIS 500 lecture notes.
Higher-order functions in OCaml. Higher-order functions A first-order function is one whose parameters and result are all "data" A second-order function.
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 Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
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.
Exercises – don’t use built in functions for these as we want the practice Write a recursive function to add up all the numbers in a list "flatten" a list.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
Programovací jazyky F# a OCaml Chapter 2. Refactoring code using functions.
Patterns in ML 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 the.
Map and Fold Building Powerful Abstractions. Hello. I’m Zach, one of Sorin’s students.
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.
1 Functional Programming and ML. 2 What’s wrong with Imperative Languages? State State Introduces context sensitivity Introduces context sensitivity Harder.
Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.
ML Datatypes.1 Standard ML Data types. ML Datatypes.2 Concrete Datatypes  The datatype declaration creates new types  These are concrete data types,
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
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.
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
F28PL1 Programming Languages Lecture 13: Standard ML 3.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads)
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Functional Programming Lecture 3 - Lists Muffy Calder.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
7/7/20161 Programming Languages and Compilers (CS 421) Dennis Griffith 0207 SC, UIUC Based in part on slides by Mattox.
10/1/20161 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
Programming Languages and Compilers (CS 421)
Principles of programming languages 12: Functional programming
Types CSCE 314 Spring 2016.
Programming Languages and Compilers (CS 421)
ML: a quasi-functional language with strong typing
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2017.
ML Again ( Chapter 7) Patterns Local variable definitions
A lightening tour in 45 minutes
CMSC 330: Organization of Programming Languages
Programming Languages and Compilers (CS 421)
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Objective caml Daniel Jackson MIT Lab for Computer Science 6898: Advanced Topics in Software Design March 18, 2002.
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2013.
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2018.
CSE-321 Programming Languages Introduction to Functional Programming
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Zach Tatlock Winter 2018.
Madhusudan Parthasarathy
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2016.
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Spring 2019.
Brett Wortzman Summer 2019 Slides originally created by Dan Grossman
CSE341: Programming Languages Lecture 6 Nested Patterns Exceptions Tail Recursion Dan Grossman Autumn 2017.
Review Previously in: Lots of language features: functions, lists, records, tuples, variants, pattern matching Today: No new language features New idioms.
Presentation transcript:

Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types

Generic types

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Types that can carry values of any type Note: Built-in tuple is generic automatically »Declaring our own generic types Generic types type MyOption = | MySome of 'a | MyNone let tup1 = ("hello", 1234) let tup2 = (12.34, false) Generic type parameter(s) Actual type argument will be used here type 'a MyOption = | MySome of 'a | MyNone OCaml-compatible syntax

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Type inference infers the type automatically Using generic types > let optNum = MySome(5);; val optNum : MyOption = MySome 5 > let optStr = MySome("abc");; val optStr : MyOption = MySome "abc" > let opt = MyNone;; val opt : MyOption > optStr = opt;; val it : bool = false Inferred type argument Tricky thing: generic value – we dont know the actual type argument yet We can use it with any other option

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Just like ordinary functions – it just works! »Automatic generalization An important aspect of F# type inference Finds the most general type of a function Writing generic functions > let getValue opt = match opt with | MySome(v) -> v | _ -> failwith "error!";; val getValue : MyOption -> 'a > getValue (MySome "hey");; val it : string = "hey" Inferred as generic argument Doesnt matter what type the value has The type of getValue is generic function

Recursive data types

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Question Can we create a data type that can represent datasets of arbitrary size, unknown at compile time (using what weve seen so far)? If yes, how can we do that? Type declarations

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Using type recursively in its declaration »We also need to terminate the recursion type List = | Cons of 'a * List | Nil let list = Cons(0, Cons(1, Cons(2, Nil))) Recursive type declarations type List = | Cons of 'a * List let list = Cons(0, Cons(1, Cons(2,...))) Recursive usage This looks like a problem! Represents an empty list

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Same as our previous list – two constructors: [] – creates an empty list :: – creates list from element and a list – concatenates two lists (inefficient) »Processing lists using pattern-matching F# list type let data = (1::(2::(3::(4::(5::[]))))) let data = 1::2::3::4::5::[] let data = [1; 2; 3; 4; 5] Right-associative Simplified syntax let firstElement = match data with | [] -> -1 | x::_ -> x Complete pattern match – covers both cases

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Processing data structures recursively List defines the structure of the data: We can follow this structure when processing: »We can express many standard operations Filtering, projection, aggregation (aka folding) Structural recursion Processing will always terminate (if data is finite)!

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Processing functions have similar structure Structurally recursive functions let rec removeOdds list = match list with | [] -> [] | x::xs -> let rest = removeOdds xs if x%2=0 then rest else x::rest let rec sumList list = match list with | [] -> 0 | x::xs -> x + (sumList xs) Return [] for empty list Recursively process the rest Join current element with the processed Return 0 for empty list Recursively sum the rest Join current element with the sum

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Sum, filtering – calculate on the way back Value is returned as the result from the function »Other operations calculate on the way forward Pass the value as argument to the recursive call Processing lists

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Calculating on the way forward – reverse »Technique called accumulator argument We accumulate the result of the function Important concept that allows tail-recursion Structurally recursive functions let rec reverse' res list = match list with | [] -> [] | x::xs -> reverse' (x::res) list let reverse list = reverse' [] list Return [] for empty list Perform calculation before recursion Recursive call

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Write a function that counts the number of elements in the list that are larger than or equal to the average (using integer division for simplicity). Using just a single traversal of the list structure! You can define a utility function foo' if you need to… Hint: Homework #1 foo [1; 2; 3; 4] = 3 // average 2 foo [1; 2; 3; 6] = 2 // average 3 foo [4; 4; 4; 4] = 4 // average 4

Tail-recursion

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Every recursive call adds a single stack frame Well can get StackOverflowException How to rewrite the function using tail-recursion? Sum list – non-tail-recursive let test2 = List.init (fun _ -> rnd.Next(– 50, 51);; let rec sumList list = match list with | [] -> 0 | x::xs -> x + sumList xs Performs addition after recursion

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Process while going forward We can drop the current stack frame when performing a tail-recursive call Sum list – tail-recursive let rec sumList' total list = match list with | [] -> total | x::xs -> let ntotal = x + total sumList' ntotal xs let sumList list = sumList' 0 list Performs addition before recursion Recursive call is the last thing!

NPRG049 Programovací jazyky OCaml a F#Tomáš Petříček, »Write a tail-recursive function that takes a list and removes all odd numbers from the list. (e.g. removeOdds [1; 2; 3; 5; 4] = [2; 4]) »Hints: 1. Tail-recursive functions do all processing when traversing the list forward. 2. Youll need to do this during two traversals of some list (both of them use accumulator and are tail-recursive) Homework #2