Programovací jazyky F# a OCaml Chapter 5. Hiding recursion using function-as-values.

Slides:



Advertisements
Similar presentations
Introduction A function is called higher-order if it takes a function as an argument or returns a function as a result. twice :: (a  a)  a  a twice.
Advertisements

Higher-order functions in ML
Programovací jazyky F# a OCaml Chapter 4. Generic and recursive types.
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.
F28PL1 Programming Languages Lecture 14: Standard ML 4.
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.
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.
0 PROGRAMMING IN HASKELL Chapter 10 - Declaring Types and Classes.
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.
Tutorial 5. Recap For a function f which takes arguments arg1, arg2,... argn, and returns type rettype, the compiler will print: f : arg1 -> arg2 ->...
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
CSE341: Programming Languages Lecture 8 Lexical Scope and Function Closures Dan Grossman Fall 2011.
CSE341: Programming Languages Lecture 7 Functions Taking/Returning Functions Dan Grossman Fall 2011.
0 PROGRAMMING IN HASKELL Chapter 7 - Higher-Order Functions.
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.
7/2/20151 Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC Based in part on slides by Mattox.
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.
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.
Functional Programming Language OCaml Tutorial 科大 - 耶鲁联合研究中心
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads)
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
CMSC 330: Organization of Programming Languages Functional Programming with OCaml.
CMSC 330: Organization of Programming Languages Maps and Folds Anonymous Functions.
CSE 130 : Spring 2011 Programming Languages Ranjit Jhala UC San Diego Lecture 6: Higher-Order Functions.
Kyung-Goo Doh Hanyang University - ERICAComputer Science & Engineering Functional Programming / Imperative Programming CSE215 Fundamentals of Program Design.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
CSE 341 : Programming Languages Lecture 8 First Class Functions Zach Tatlock Spring 2014.
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,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
3/8/20161 Programming Languages and Compilers (CS 421) Reza Zamani Based in part on slides by Mattox Beckman, as updated.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
CSE 341 : Programming Languages Lecture 9 Lexical Scope, Closures Zach Tatlock Spring 2014.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
7/7/20161 Programming Languages and Compilers (CS 421) Dennis Griffith 0207 SC, UIUC Based in part on slides by Mattox.
Conditional Expressions
ML: a quasi-functional language with strong typing
Programming Languages and Compilers (CS 421)
A lightening tour in 45 minutes
Haskell Chapter 4.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CMSC 330: Organization of Programming Languages
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Nicholas Shahan Spring 2016
PROGRAMMING IN HASKELL
Agenda SML Docs First-Class Functions Examples Standard Basis
Agenda SML Docs First-Class Functions Examples Standard Basis
CSE 341 Section 5 Winter 2018.
Higher Order Functions
PROGRAMMING IN HASKELL
CSE 341 Section 3 Nick Mooney Spring 2017.
CSE-321 Programming Languages Introduction to Functional Programming
Madhusudan Parthasarathy
PROGRAMMING IN HASKELL
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 5. Hiding recursion using function-as-values

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Writing recursive functions explicitly How to avoid repeating the same pattern? »Parameterized and higher-order functions Initial value: 1 for mul and 0 for sum Aggregation function: * for mul and + for sum Hiding the recursive part let rec sum list = match list with | [] -> 0 | x::xs -> x + (sum xs) let rec mul list = match list with | [] -> 1 | x::xs -> x * (mul xs)

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Generalized function for aggregation »Automatic generalization Infers the most general type of the function! List processing with HOFs > let rec aggregate f initial list = match list with | [] -> initial | x::xs -> f (aggregate f initial xs) x;; val aggregate : ('a -> 'b -> 'a) -> 'b -> 'a list -> 'b > aggregate (+) 0 [1.. 10];; val it : int = 55 > aggregate (fun st el -> el::st) [] [1.. 10];; val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] “some” state Previously unexpected use!

Processing options using HOFs

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Read two integers and add them Fail (return None) when the input is invalid Reading two integers let readInput() = let (succ, num) = Int32.TryParse(Console.ReadLine()) if succ then Some(num) else None let readAndAdd() = match readInput() with | None -> None | Some(n) -> match (readInput()) with | None -> None | Some(m) -> Some(n + m) First input is wrong Read second value Second input is wrong Finally!

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, map – apply calculation to a value (if there is any) and wrap the value in option with same structure bind – apply calculation to a value (if there is any), the calculation can fail (returns another option) Simplifying using HOFs let readAndAdd() = match readInput() with | None -> None | Some(n) -> readInput() |> Option.map ((+) n) let readAndAdd() = readInput() |> Option.bind (fun n -> readInput() |> Option.map ((+) n))

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, Working with options in F# DEMO

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Working with options in F# map – Calculates a new value if there is a value bind – Calculates a new option if there is a value exists – True if a value exists & matches predicate fold – Aggregates “all” values into a single value F# library functions

List processing using HOFs

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Processing lists in F# map – Generates a new value for each element filter – Creates list filtered using predicate fold – Aggregate all elements into “some state” foldBack – same as fold, but from the end collect (aka bind) – generate list of data for every element and merge all created lists rev – reverse the list Seq.unfold – builds a sequence (convertible to list) F# library functions

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, Working with lists in F# DEMO

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Pipelining ( |> operator) »Composition ( >> operator) Pipelining and composition [1.. 10] |> List.filter (fun n -> n%2=0) |> List.map (fun n -> n*n) // Implementation is very simple! let (|>) v f = f v [(1, "one"); (2, "two"); (3, "three")] |> List.map (snd >> String.length) // Implementation is very simple! let (>>) f g x = g (f x) Pass the value eon the left side to the function on the right Creates a function that performs f, then g.

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »fold processes data on the way to the front, foldBack on the way back (to the beginning). »Write a more general function that allows us to do both things at once. Use it to implement: fold & foldBack traverse homework (from Ch. 4, slide 14) Homework #1

Abstract data types

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Defines a set and an operation on the set »Monoid: is a set M, operation, element e: Operation: : M × M → M Associativity: (a b) c = a (b c) Identity: e a = a e = a »Natural numbers: set N, 0 ∈ N, operation S Successor: S : N → N Plus a lot of axioms defines natural numbers Algebraic definitions

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »Describe type using operations we can use »For example, a list is L and operations: Operation:map : ('a → 'b) → L → L Operation:fold : ('a → 'b → ‘a) → 'a → L → ‘a There are also some axioms… map g (map f l) == map (f >> g) l fold g v (map f l) == fold (fun s x -> g s (f x)) v l »Abstract description of types (as in algebra ) Abstract data type

NPRG049— Programovací jazyky OCaml a F#Tomáš Petříček, »What is a monoid in programming language? Monoid is M and e ∈ M operation f : M -> M -> M Associativity: f (f a b) c = f a (f b c) Identity: f e a = f a e = e »Which F# data types are monoids? Numeric : Int (+, 0), Int (*, 1) Strings: (+, "") + is concatenation Lists: is concatenation Back to monoids…

Representing other data structures