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

Similar documents
CSE341 Section 3. Standard-Library Docs, First-Class Functions, & More

List Functions, and Higher-Order Functions

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

Programming Languages and Techniques (CIS120)

School of Computer Science

02157 Functional Programming Tagged values and Higher-order list functions

CS 321 Programming Languages

02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen

Introduction to OCaml

Programovací jazyky F# a OCaml. Chapter 6. Sequence expressions and computation expressions (aka monads)

F# - LISTS. In this method, you just specify a semicolon-delimited sequence of values in square brackets. For example

02157 Functional Programming. Michael R. Ha. Tagged values and Higher-order list functions. Michael R. Hansen

CSCI 2041: First Class Functions

CSE 130 [Winter 2014] Programming Languages

CSCI-GA Scripting Languages

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

FUNCTIONAL PROGRAMMING

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Lecture: Functional Programming

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Why OCaml? Introduction to Objective Caml. Features of OCaml. Applications written in OCaml. Stefan Wehr

Introduction to Objective Caml

Chapter 3 Linear Structures: Lists

Problem Set CVO 103, Spring 2018

CS 11 Ocaml track: lecture 2

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Chapter 3 Linear Structures: Lists

Functional Programming. Pure Functional Programming

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

CMSC 330, Fall 2013, Practice Problems 3

Haskell An Introduction

Write: evens. evens [] ====> [] evens [1;2;3;4] ====> [2;4]

CSE 341 Section 5. Winter 2018

Recursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. Higher-Order Functions

Last time: generic programming

Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

Patterns The Essence of Functional Programming

INF121: Functional Algorithmic and Programming

This assignment has four parts. You should write your solution to each part in a separate file:

A Brief Introduction to Standard ML

CMSC 330: Organization of Programming Languages

Functional Programming. Overview. Topics. Definition n-th Fibonacci Number. Graph

CS3110 Spring 2016 Lecture 6: Modules

SNU Programming Language Theory

Functional Programming. Lecture 2: Algebra

Programming Languages and Techniques (CIS120)

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

CSci 4223 Principles of Programming Languages

Programming Languages and Techniques (CIS120)

CSE341 Spring 2016, Midterm Examination April 29, 2016

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming and Haskell. Aden Seaman

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

INTRODUCTION TO FUNCTIONAL PROGRAMMING

Abram Hindle Kitchener Waterloo Perl Monger October 19, 2006

CSCE 314 Programming Languages

CSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions

CSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

Shell CSCE 314 TAMU. Higher Order Functions

Programming Languages and Techniques (CIS120)

Topic 5: Examples and higher-order functions

Quiz 2 CSCI 1103 Computer Science I Honors KEY. Tuesday November 8, 2016 Instructor Muller Boston College. Fall 2016

COSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming

Functional Programming for Imperative Programmers

These notes are intended exclusively for the personal usage of the students of CS352 at Cal Poly Pomona. Any other usage is prohibited without

CSE341, Fall 2011, Midterm Examination October 31, 2011

CSE 130 [Winter 2014] Programming Languages

CS 4110 Programming Languages & Logics. Lecture 28 Recursive Types

CSE341 Spring 2016, Midterm Examination April 29, 2016

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Recap: ML s Holy Trinity. Story So Far... CSE 130 Programming Languages. Datatypes. A function is a value! Next: functions, but remember.

CSE 130 Programming Languages. Datatypes. Ranjit Jhala UC San Diego

CSE 130: Programming Languages. Polymorphism. Ranjit Jhala UC San Diego

Reactive programming, WinForms,.NET. Björn Dagerman

Advanced Type System Features Tom Schrijvers. Leuven Haskell User Group

CIS 500 Software Foundations Midterm I

Typed Racket: Racket with Static Types

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE 130 Programming Languages. Lecture 3: Datatypes. Ranjit Jhala UC San Diego

The Substitution Model. Nate Foster Spring 2018

CMSC330 Spring 2014 Midterm 2 Solutions

Monads. Prof. Clarkson Fall Today s music: Vámanos Pal Monte by Eddie Palmieri

L3 Programming September 19, OCaml Cheatsheet

Topic 7: Algebraic Data Types

Shell CSCE 314 TAMU. Functions continued

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

CMSC 330, Fall 2013, Practice Problem 3 Solutions

Modules and Representation Invariants

MP 2 Continuation-Passing Style

Lecture 4: Higher Order Functions

Homework 3 COSE212, Fall 2018

Programovací jazyky F# a OCaml. Chapter 3. Composing primitive types into data

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Programming Languages and Techniques (CIS120)

CMSC 330: Organization of Programming Languages. OCaml Higher Order Functions

Recap: ML s Holy Trinity

Transcription:

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

Hiding the recursive part» Writing recursive functions explicitly 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) 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

List processing with HOFs» Generalized function for aggregation > let rec aggregate f initial list = match list with some state [] -> initial x::xs -> f (aggregate f initial xs) x;; val aggregate : ('a -> 'b -> 'a) -> 'b -> 'a list -> 'b» Automatic generalization Infers the most general type of the function! > aggregate (+) 0 [1.. 10];; Previously val it : int = 55 unexpected use! > aggregate (fun st el -> el::st) [] [1.. 10];; val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

Processing options using HOFs

Reading two integers» Read two integers and add them Fail (return None) when the input is invalid 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!

Simplifying using HOFs map apply calculation to a value (if there is any) and wrap the value in option with same structure let readandadd() = match readinput() with None -> None Some(n) -> readinput() > Option.map ((+) n) bind apply calculation to a value (if there is any), the calculation can fail (returns another option) let readandadd() = readinput() > Option.bind (fun n -> readinput() > Option.map ((+) n))

DEMO Working with options in F#

F# library functions» 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

List processing using HOFs

F# library functions» 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)

DEMO Working with lists in F#

Pipelining and composition» Pipelining ( > operator) [1.. 10] > List.filter (fun n -> n%2=0) > List.map (fun n -> n*n) // Implementation is very simple! let ( >) v f = f v» Composition (>> operator) [(1, "one"); (2, "two"); (3, "three")] > List.map (snd >> String.length) Pass the value eon the left side to the function on the right // Implementation is very simple! let (>>) f g x = g (f x) Creates a function that performs f, then g.

Homework #1» 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)

Abstract data types

Algebraic definitions» 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

Abstract data type» Describe type using operations we can use» For example, a list is L<'a> and operations: Operation: map : ('a 'b) L<'a> L<'b> Operation: fold : ('a 'b a) 'a L< b> 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 )

Back to monoids» 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

Representing other data structures