Higher-Order Functions
|
|
- Maximilian Barber
- 5 years ago
- Views:
Transcription
1 Higher-Order Functions Tjark Weber Functional Programming 1 Based on notes by Pierre Flener, Jean-Noël Monette, Sven-Olof Nyström Tjark Weber (UU) Higher-Order Functions 1 / 1
2 Tail Recursion Tjark Weber (UU) Higher-Order Functions 2 / 1
3 Exercise: A Simple Matrix Can you find a linear tail-recursive function, a linear function that is not tail-recursive, a quadratic but tail-recursive function, and a quadratic function that is not tail-recursive? Tail-recursive Not tail-recursive Linear?? Quadratic?? Tjark Weber (UU) Higher-Order Functions 3 / 1
4 Higher-Order Functions Tjark Weber (UU) Higher-Order Functions 4 / 1
5 Today Tjark Weber (UU) Higher-Order Functions 5 / 1
6 Definition, Introductory Examples Table of Contents Tjark Weber (UU) Higher-Order Functions 6 / 1
7 Definition, Introductory Examples Higher-Order Functions A higher-order function is a function that Remarks: takes functions as arguments or returns a function. This is hard to do in most imperative programming languages. This is a very powerful mechanism. Abstraction, code re-use Tjark Weber (UU) Higher-Order Functions 7 / 1
8 Definition, Introductory Examples An Example From Mathematics The derivative in calculus maps (differentiable) functions to functions. Tjark Weber (UU) Higher-Order Functions 8 / 1
9 Definition, Introductory Examples An Example From Last Lecture fun time f = l e t v a l t i m e r = Timer. startcputimer ( ) v a l = f ( ) ( do the a c t u a l work ) i n Timer. checkcputimes t i m e r end Here, f is a function (of type unit > a). Thus, time is a higher-order function. Tjark Weber (UU) Higher-Order Functions 9 / 1
10 Definition, Introductory Examples Another Example: Function Composition A function that takes two functions and returns a function! fun o (f,g) x = f (g x); infix o; o is predefined in SML. No need to define it yourself. Example: fun add1 x = x + 1; (add1 o add1) 42; Tjark Weber (UU) Higher-Order Functions 10 / 1
11 Definition, Introductory Examples Insertion Sort on Integers fun insert x [] = [x] insert x (y :: ys) = if x < y then x :: y :: ys else y :: ( insert x ys) fun isort [] = [] isort (x :: xs) = insert x ( isort xs) Which part of the code is specific to integers? Tjark Weber (UU) Higher-Order Functions 11 / 1
12 Definition, Introductory Examples Insertion Sort on Any Type fun insert order x [] = [x] insert order x (y :: ys) = if order (x,y) then x :: y :: ys else y :: ( insert order x ys) fun isort order [] = [] isort order (x :: xs) = insert order x ( isort order xs) What is the type of the different functions? Tjark Weber (UU) Higher-Order Functions 12 / 1
13 Definition, Introductory Examples Example (cont.) > isort (op <) [6,3,0,1,7,8,5,9,2,4]; val it = [0,1,2,3,4,5,6,7,8,9]: int list > isort (op >) [6,3,0,1,7,8,5,9,2,4]; val it = [9,8,7,6,5,4,3,2,1,0]: int list > isort String.< [ one, two, three, four, five, six ]; val it = [ five, four, one, six, three, two ]: string > isort (op <); val it = fn: int list > int list > isort String.< ; val it = fn: string list > string list > isort (fn ((,s1 ),(,s2)) => String.< (s1,s2)) [(1, one ),(2, two ),(3, three ),(4, four ),(5, five ),(6, six )]; val it = [(5, five ),(4, four ),(1, one ),(6, six ),(3, three ), (2, two )]: ( int string ) list list Tjark Weber (UU) Higher-Order Functions 13 / 1
14 Definition, Introductory Examples Another Example: pair > fun pair (f,g) x = (f x, g x); val pair = fn: ( a > b) ( a > c) > a > b c > pair (add1, add1 o add1); val it = fn: int > int int > it 42; val it = (43,44): int int > pair ( pair (add1, add1 o add1), add1); val it = fn: int > (int int) int > it 42; val it = ((43,44),43): ( int int ) int Tjark Weber (UU) Higher-Order Functions 14 / 1
15 Higher-Order Functions on Lists Table of Contents Tjark Weber (UU) Higher-Order Functions 15 / 1
16 Higher-Order Functions on Lists Reflection on the Definition of sum fun sum [] = 0 sum (x::xs) = x + sum xs There are only two places in the function definition that are specific for computing a sum: +, combining data 0, result for empty list Tjark Weber (UU) Higher-Order Functions 16 / 1
17 Higher-Order Functions on Lists A Generalization Let s define a function reduce so that reduce + 0 is equal to sum: fun reduce f z [] = z reduce f z (x :: xs) = f (x,reduce f z xs) fun reduce f z = (fn [] => z (x :: xs) => f (x,reduce f z xs)) Note the similarity between reduce and sum. Tjark Weber (UU) Higher-Order Functions 17 / 1
18 Higher-Order Functions on Lists Generalization (cont.) Now, sum can be defined as fun sum xs = reduce (op +) 0 xs val sum = reduce (op +) 0 Tjark Weber (UU) Higher-Order Functions 18 / 1
19 Higher-Order Functions on Lists Other Uses of reduce What will the following compute? reduce (op ) 1 [1,2,3,4]; reduce Int. max 0 [1,2,3,44,5,6]; reduce (fn(x,y) => x::y) [] [1,2,3,4]; reduce (fn(x,y) => x::y) [5,6,7] [1,2,3,4]; reduce (fn(x,y) => x::x::y) [] [1,2,3,4]; reduce [] [[1,2],[34],[5,6,7,89]]; Tjark Weber (UU) Higher-Order Functions 19 / 1
20 Higher-Order Functions on Lists Higher-Order Functions on Lists Several functions are very useful to define operations on lists. > map; val it = fn: ( a > b) > a list > b list > foldr ; val it = fn: ( a b > b) > b > a list > b > foldl ; val it = fn: ( a b > b) > b > a list > b > List. filter ; val it = fn: ( a > bool) > a list > a list Those functions are predefined in ML, but we will see the details. Tjark Weber (UU) Higher-Order Functions 20 / 1
21 Higher-Order Functions on Lists The map Function Apply the same operation on all the elements of a list. ( PRE: (none) POST: [f(a 1),f(a 2),..., f(a n )], if L = [a 1,a 2,..., a n] ) > fun map f [ ] = [ ] map f (x :: xs) = f x :: map f xs; val map = fn: ( a > b) > a list > b list > fun square x = x x; val square = fn: int > int > map square [1,2,3,4]; val it = [1,4,9,16]: int list > map (fn(x)=> if x < 3 then 0 else x) [1,2,3,4]; val it = [0,0,3,4]: int list Tjark Weber (UU) Higher-Order Functions 21 / 1
22 Higher-Order Functions on Lists The map Function (cont.) > map square; val it = fn: int list > int list > map (map square); val it = fn: int list list > int list list > map (map square) [[1,2,34],[5]]; val it = [[1,4,1156],[25]]: int list list > map String.<; val it = fn: ( string string ) list > bool list > map String.< [( a, ab ), ( hello, bye )]; val it = [true, false ]: bool list Tjark Weber (UU) Higher-Order Functions 22 / 1
23 Higher-Order Functions on Lists Foldr and foldl fun foldr f b [] = b foldr f b (x :: xs) = f(x, foldr f b xs ); fun foldl f b [] = b foldl f b (x :: xs) = foldl f (f (x, b)) xs; Do they remind you of any function you have seen before? Which one is tail-recursive? Tjark Weber (UU) Higher-Order Functions 23 / 1
24 Higher-Order Functions on Lists Examples Sum the elements of the list. foldr (op +) 0 [0,2,21,4,6]; foldl (op +) 0 [0,2,21,4,6]; Are they equivalent? Which one would you use? Why? Tjark Weber (UU) Higher-Order Functions 24 / 1
25 Higher-Order Functions on Lists Examples (cont.) Check that all elements of a list are even foldr (fn (x,y) => y andalso x mod 2 = 0) true [0,2,21,4,6]; foldl (fn (x,y) => y andalso x mod 2 = 0) true [0,2,21,4,6]; Are they equivalent? Which one would you use? Why? Tjark Weber (UU) Higher-Order Functions 25 / 1
26 Higher-Order Functions on Lists Examples (cont.) Compare foldr (op ::) []; foldl (op ::) []; Are they equivalent? Which one would you use? Why? Tjark Weber (UU) Higher-Order Functions 26 / 1
27 Higher-Order Functions on Lists Examples (cont.) What does this function compute? fun firsteven (x,none) = if x mod 2 = 0 then SOME x else NONE firsteven (, SOME y) = SOME y; Compare foldl foldr firsteven NONE; firsteven NONE; Are they equivalent? Which one would you use for what? Tjark Weber (UU) Higher-Order Functions 27 / 1
28 Higher-Order Functions on Lists More Examples Try foldl (fn(x,n) => n+1) 0 foldr (fn(x,n) => n+1) 0 foldr (fn(x,n) => x) 0 foldl (fn(x,n) => x) 0 fun mystery f = foldr (fn (x,n) => f x :: n) []; Tjark Weber (UU) Higher-Order Functions 28 / 1
29 Higher-Order Functions on Lists Filter ( PRE: (none) POST: the list of elements of the list for which p is true ) fun filter p [] = [] filter p (x :: xs) = if p x then x :: filter p xs else filter p xs; Examples: filter (fn x => x<6); filter (fn x => x<6) [6,3,0,1,8,5,9,3]; Tjark Weber (UU) Higher-Order Functions 29 / 1
30 More Examples Table of Contents Tjark Weber (UU) Higher-Order Functions 30 / 1
31 More Examples Folding Over Integers Fold over integers (really natural numbers) gives us a general way to recurse over natural numbers: fun foldint f b 0 = b foldint f b n = foldint f (f(b,n)) (n 1); foldint (op + ) 0 5; foldint (op ) 1 5; foldint (fn ((a,b), ) => (a+b, a)) (1,1) 10; Tjark Weber (UU) Higher-Order Functions 31 / 1
32 More Examples Folding Over Integers (cont.) fun td a = foldint (fn (b,n) => b andalso (n <= 1 orelse a mod n <> 0)) true (a 1); fun primes n = foldint (fn ( l, n) => if td n then n:: l else l ) [] n; Tjark Weber (UU) Higher-Order Functions 32 / 1
33 More Examples twice and ntimes We can define a function that tells us how to do something twice: fun twice f = f o f ; fun add1 x = x+1; twice add1 56; Or more generally, do something n times: fun ntimes 0 f x = x ntimes n f x = ntimes (n 1) f (f x); ntimes 42 twice ; Tjark Weber (UU) Higher-Order Functions 33 / 1
34 Example: Polymorphic Ordered Binary Tree Table of Contents Tjark Weber (UU) Higher-Order Functions 34 / 1
35 Example: Polymorphic Ordered Binary Tree Binary Search Trees A Binary search tree is a binary tree which is ordered, i.e. All values in the left subtree are smaller than the value of the root. All values in the right subtree are larger than the value of the root. The order can be defined for any type. We will consider the values to be pairs: The first element is the key. The second is the value that we want to associate with the key. i.e. we define a dictionary. Tjark Weber (UU) Higher-Order Functions 35 / 1
36 Example: Polymorphic Ordered Binary Tree Binary Search Trees datatype ( a, b) bstree = Void Bst of ( a, b) bstree ( a b) ( a, b) bstree; Note: We want the key to be of some equality type. The order is not part of the datatype. It is (unfortunately) possible to build a bstree that is not ordered. Tjark Weber (UU) Higher-Order Functions 36 / 1
37 Example: Polymorphic Ordered Binary Tree Retrieving an Element ( PRE: the tree is ordered. POST: if the tree contains the key, return the corresponding value embedded in SOME. NONE otherwise ) fun retrieve lessthan k Void = NONE retrieve lessthan key (Bst ( left,( k,v), right )) = if key = k then SOME v else if lessthan (key,k) then retrieve lessthan key left else retrieve lessthan key right ; Tjark Weber (UU) Higher-Order Functions 37 / 1
38 Example: Polymorphic Ordered Binary Tree Retrieving an Element (cont.) We may use the datatype order instead: fun retrieve compare k Void = NONE retrieve compare key (Bst ( left,( k,v), right )) = case compare (key,k) of EQUAL => SOME v LESS => retrieve compare key left GREATER => retrieve compare key right; Tjark Weber (UU) Higher-Order Functions 38 / 1
39 Example: Polymorphic Ordered Binary Tree Inserting an Element ( PRE: The tree is ordered. POST: If the tree contains the key, a tree with the value replaced. Otherwise, a tree with the (key, value) pair inserted such that the tree is ordered. ) fun insert compare (key,value) Void = Bst(Void,(key,value ), Void) insert compare (key,value) (Bst ( left,( k,v), right )) = case compare (key,k) of EQUAL => Bst (left,(k,value),right) LESS => Bst(insert compare (key,value) left, (k,v), right ) GREATER => Bst(left,(k,v),insert compare (key,value) right ); Exercise: Specify and realise the exists and delete functions. (Delete is a bit more difficult.) Tjark Weber (UU) Higher-Order Functions 39 / 1
40 Example: Polymorphic Ordered Binary Tree Functional Datatype Consider again the previous definition of bstree and its shortcomings: The functional argument compare must be passed at each call. The compare order is not global to the binary search tree. Let s introduce the order in a new datatype: datatype ( a, b) bstree = Void Bst of ( a, b) bstree ( a b) ( a, b) bstree; type ( a) ordering = ( a a) > order; datatype ( a, b) obstree = OrdBsTree of a ordering ( a, b) bstree; Tjark Weber (UU) Higher-Order Functions 40 / 1
41 Example: Polymorphic Ordered Binary Tree Inserting an Element fun emptytree compare = OrdBsTree (compare, Void); fun insert (key, value) OrdBsTree (compare, tree) = let fun insert Void = (key,value) insert (Bst ( left,( k,v), right )) = case compare (key,k) of EQUAL => Bst (left,(k,value),right) LESS => Bst(insert left, (k,v), right ) GREATER => Bst(left,(k,v),insert right ) in OrdBstTree (compare, insert tree ) end; Tjark Weber (UU) Higher-Order Functions 41 / 1
42 Higher-Order Functions on Trees Table of Contents Tjark Weber (UU) Higher-Order Functions 42 / 1
43 Higher-Order Functions on Trees Higher-Order Functions on Trees Like for lists, it is possible to define generic functions on trees. mapbt applies some function on all elements of the tree. Different folding functions can be defined. We cover here binary trees, but the same might be done for other types of trees. Tjark Weber (UU) Higher-Order Functions 43 / 1
44 Higher-Order Functions on Trees Mapping and Reducing a Binary Tree datatype ( a) btree = Vd Bt of a a btree a btree ; fun mapbt f Vd = Vd mapbt f (Bt(v, l, r)) = Bt(f v, mapbt f l, mapbt f r ); fun reducebt f z Vd = z reducebt f z (Bt(v, l, r)) = f (v,reducebt f z l,reducebt f z r ); mapbt abs; reducebt (fn (v, l, r) => 1 + l + r) 0; reducebt (fn (v, l, r) => 1 + Int.max(l,r)) 0; reducebt (fn (v, l, r) => r) []; reducebt (fn (v, l, r) => Bt(v,r,l)) Vd; Tjark Weber (UU) Higher-Order Functions 44 / 1
45 Higher-Order Functions on Trees Exercises Use reducebt to compute if a btree is ordered (according to some given order). Use reducebt to transform a btree into a bstree. Define a function map on finitely branching trees (cf. assignment 2). Tjark Weber (UU) Higher-Order Functions 45 / 1
Lecture 2: The Basis of SML
Lecture 2: The Basis of SML Jean-Noël Monette Functional Programming 1 September 9, 2013 Based on notes by Pierre Flener, Sven-Olof Nyström Jean-Noël Monette (UU) Lecture 2: The Basis of SML 1 / 73 Today
More informationCSci 4223 Principles of Programming Languages
CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,
More informationF28PL1 Programming Languages. Lecture 14: Standard ML 4
F28PL1 Programming Languages Lecture 14: Standard ML 4 Polymorphic list operations length of list base case: [] ==> 0 recursion case: (h::t) => 1 more than length of t - fun length [] = 0 length (_::t)
More informationInductive Data Types
Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old
More informationRecursion. Tjark Weber. Functional Programming 1. Based on notes by Sven-Olof Nyström. Tjark Weber (UU) Recursion 1 / 37
Tjark Weber Functional Programming 1 Based on notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 37 Background FP I / Advanced FP FP I / Advanced FP This course (Functional Programming I) (5 hp,
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Two constructors for lists... 3.2 2. Lists... 3.3 3. Basic operations... 3.5 4. Constructors and pattern matching... 3.6 5. Simple operations on lists... 3.9
More informationRecursion. Lars-Henrik Eriksson. Functional Programming 1. Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström
Lars-Henrik Eriksson Functional Programming 1 Based on a presentation by Tjark Weber and notes by Sven-Olof Nyström Tjark Weber (UU) Recursion 1 / 41 Comparison: Imperative/Functional Programming Comparison:
More informationProcessadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)
Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine
More informationChapter 3 Linear Structures: Lists
Plan Chapter 3 Linear Structures: Lists 1. Lists... 3.2 2. Basic operations... 3.4 3. Constructors and pattern matching... 3.5 4. Polymorphism... 3.8 5. Simple operations on lists... 3.11 6. Application:
More informationLecture 19: Functions, Types and Data Structures in Haskell
The University of North Carolina at Chapel Hill Spring 2002 Lecture 19: Functions, Types and Data Structures in Haskell Feb 25 1 Functions Functions are the most important kind of value in functional programming
More informationGeneral Computer Science (CH ) Fall 2016 SML Tutorial: Practice Problems
General Computer Science (CH08-320101) Fall 2016 SML Tutorial: Practice Problems November 30, 2016 Abstract This document accompanies the traditional SML tutorial in GenCS. It contains a sequence of simple
More informationExercises on ML. Programming Languages. Chanseok Oh
Exercises on ML Programming Languages Chanseok Oh chanseok@cs.nyu.edu Dejected by an arcane type error? - foldr; val it = fn : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b - foldr (fn x=> fn y => fn z => (max
More informationA general introduction to Functional Programming using Haskell
A general introduction to Functional Programming using Haskell Matteo Rossi Dipartimento di Elettronica e Informazione Politecnico di Milano rossi@elet.polimi.it 1 Functional programming in a nutshell
More informationIntroduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions
Introduction to SML Basic Types, Tuples, Lists, Trees and Higher-Order Functions Michael R. Hansen mrh@imm.dtu.dk Informatics and Mathematical Modelling Technical University of Denmark c Michael R. Hansen,
More informationA Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1
A Third Look At ML Chapter Nine Modern Programming Languages, 2nd ed. 1 Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order
More informationCSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011
CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging
More informationCSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013
CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging
More informationML Built-in Functions
ML Built-in Functions Since ML is a functional programming language, many of its built-in functions are concerned with function application to objects and structures. In ML, built-in functions are curried
More informationAustralian researchers develop typeface they say can boost memory, that could help students cramming for exams.
Font of all knowledge? Australian researchers develop typeface they say can boost memory, that could help students cramming for exams. About 400 university students took part in a study that found a small
More informationSML A F unctional Functional Language Language Lecture 19
SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list
More informationCSE 341 Section 5. Winter 2018
CSE 341 Section 5 Winter 2018 Midterm Review! Variable Bindings, Shadowing, Let Expressions Boolean, Comparison and Arithmetic Operations Equality Types Types, Datatypes, Type synonyms Tuples, Records
More informationCSCE 314 Programming Languages
CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee 1 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as
More informationChapter 6 Abstract Datatypes
Plan Chapter 6 Abstract Datatypes (Version of 17 November 2005) 1. Application: correctly parenthesised texts...... 6.2 2. An abstract datatype for stacks................ 6.6 3. Realisation of the stack
More informationShell CSCE 314 TAMU. Higher Order Functions
1 CSCE 314: Programming Languages Dr. Dylan Shell Higher Order Functions 2 Higher-order Functions A function is called higher-order if it takes a function as an argument or returns a function as a result.
More informationCSE 130 [Winter 2014] Programming Languages
CSE 130 [Winter 2014] Programming Languages Higher-Order Functions! Ravi Chugh! Jan 23 Today s Plan A little more practice with recursion Base Pattern Base Expression Induction Pattern Induction Expression
More informationCSc 372. Comparative Programming Languages. 11 : Haskell Higher-Order Functions. Department of Computer Science University of Arizona
CSc 372 Comparative Programming Languages 11 : Haskell Higher-Order Functions Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2010 Christian Collberg Higher-Order Functions
More informationCSc 520 Principles of Programming Languages. Currying Revisited... Currying Revisited. 16: Haskell Higher-Order Functions
Higher-Order Functions CSc 520 Principles of Programming Languages 16: Haskell Higher-Order Functions Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright
More informationLists. Michael P. Fourman. February 2, 2010
Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce
More informationCS 340 Spring 2019 Midterm Exam
CS 340 Spring 2019 Midterm Exam Instructions: This exam is closed-book, closed-notes. Electronic devices of any kind are not permitted. Write your final answers, tidily, in the boxes provided. Scratch
More informationCSE341 Section 3. Standard-Library Docs, First-Class Functions, & More
CSE341 Section 3 Standard-Library Docs, First-Class Functions, & More Adapted from slides by Daniel Snitkovskiy, Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman Agenda 1. SML Docs Standard
More informationCITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators
CITS3211 FUNCTIONAL PROGRAMMING 6. Folding operators Summary: This lecture discusses an important group of higher order functions known as the folding operators. Almost any recursive function over lists
More informationA list is a finite sequence of elements. Elements may appear more than once
Standard ML Lists ML Lists.1 Lists A list is a finite sequence of elements. [3,5,9] ["a", "list" ] [] Elements may appear more than once [3,4] [4,3] [3,4,3] [3,3,4] Elements may have any type. But all
More informationHaskell Overview II (2A) Young Won Lim 8/23/16
(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published
More informationPROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions
PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}
More informationHaskell Overview II (2A) Young Won Lim 8/9/16
(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published
More informationStandard ML. Data types. ML Datatypes.1
Standard ML Data types ML Datatypes.1 Concrete Datatypes The datatype declaration creates new types These are concrete data types, not abstract Concrete datatypes can be inspected - constructed and taken
More informationCSE341, Fall 2011, Midterm Examination October 31, 2011
CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.
More informationCSE341 Autumn 2017, Midterm Examination October 30, 2017
CSE341 Autumn 2017, Midterm Examination October 30, 2017 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please
More informationCSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides
CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh
More informationLogic - CM0845 Introduction to Haskell
Logic - CM0845 Introduction to Haskell Diego Alejandro Montoya-Zapata EAFIT University Semester 2016-1 Diego Alejandro Montoya-Zapata (EAFIT University) Logic - CM0845 Introduction to Haskell Semester
More informationFall Lecture 3 September 4. Stephen Brookes
15-150 Fall 2018 Lecture 3 September 4 Stephen Brookes Today A brief remark about equality types Using patterns Specifying what a function does equality in ML e1 = e2 Only for expressions whose type is
More informationLecture 4: Higher Order Functions
Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function
More informationHandout 2 August 25, 2008
CS 502: Compiling and Programming Systems Handout 2 August 25, 2008 Project The project you will implement will be a subset of Standard ML called Mini-ML. While Mini- ML shares strong syntactic and semantic
More informationThe Haskell HOP: Higher-order Programming
The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments
More informationCSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions
1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions
More informationPROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions
PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product
More informationF28PL1 Programming Languages. Lecture 12: Standard ML 2
F28PL1 Programming Languages Lecture 12: Standard ML 2 Declaration introduce a variable associate identifier with value - val identifier = expression; > val identifier = value : type identifier - any sequence
More informationA Brief Introduction to Standard ML
A Brief Introduction to Standard ML Specification and Verification with Higher-Order Logic Arnd Poetzsch-Heffter (Slides by Jens Brandt) Software Technology Group Fachbereich Informatik Technische Universität
More informationCSE 341 Sample Midterm #2
1. s For each ML expression in the left-hand column of the table below, indicate in the right-hand column its value. Be sure to (e.g., 7.0 rather than 7 for a real; Strings in quotes e.g. "hello"; true
More informationCSE 505. Lecture #9. October 1, Lambda Calculus. Recursion and Fixed-points. Typed Lambda Calculi. Least Fixed Point
Lambda Calculus CSE 505 Lecture #9 October 1, 2012 Expr ::= Var λ Var. Expr (Expr Expr) Key Concepts: Bound and Free Occurrences Substitution, Reduction Rules: α, β, η Confluence and Unique Normal Form
More informationMini-ML. CS 502 Lecture 2 8/28/08
Mini-ML CS 502 Lecture 2 8/28/08 ML This course focuses on compilation techniques for functional languages Programs expressed in Standard ML Mini-ML (the source language) is an expressive core subset of
More information02157 Functional Programming. Michael R. Ha. Disjoint Unions and Higher-order list functions. Michael R. Hansen
Disjoint Unions and Higher-order list functions nsen 1 DTU Compute, Technical University of Denmark Disjoint Unions and Higher-order list functions MRH 27/09/2018 Overview Recap Disjoint union (or Tagged
More informationProblem Set CVO 103, Spring 2018
Problem Set CVO 103, Spring 2018 Hakjoo Oh Due: 06/12 (in class) Problem 1 The Fibonacci numbers can be defined as follows: 0 if n = 0 fib(n) = 1 if n = 1 fib(n 1) + fib(n 2) otherwise Write in OCaml the
More informationA Fourth Look At ML. Chapter Eleven Modern Programming Languages, 2nd ed. 1
A Fourth Look At ML Chapter Eleven Modern Programming Languages, 2nd ed. 1 Type Definitions Predefined, but not primitive in ML: datatype bool = true false; Type constructor for lists: datatype 'element
More informationFunctional Programming - 2. Higher Order Functions
Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class
More informationCSE341 Spring 2016, Midterm Examination April 29, 2016
CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please
More informationIt is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis
Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis
More informationCSE3322 Programming Languages and Implementation
Monash University School of Computer Science & Software Engineering Sample Exam 2003 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.
More informationIntroduction to Programming: Lecture 6
Introduction to Programming: Lecture 6 K Narayan Kumar Chennai Mathematical Institute http://www.cmi.ac.in/~kumar 28 August 2012 Example: initial segments Write a Haskell function initsegs which returns
More informationCSE3322 Programming Languages and Implementation
Monash University School of Computer Science & Software Engineering Sample Exam 2004 CSE3322 Programming Languages and Implementation Total Time Allowed: 3 Hours 1. Reading time is of 10 minutes duration.
More informationA quick introduction to SML
A quick introduction to SML CMSC 15300 April 9, 2004 1 Introduction Standard ML (SML) is a functional language (or higherorder language) and we will use it in this course to illustrate some of the important
More informationCSE341, Fall 2011, Midterm Examination October 31, 2011
CSE341, Fall 2011, Midterm Examination October 31, 2011 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.
More informationIf we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of
If we have a call (map slow-function long-list where slow-function executes slowly and long-list is a large data structure, we can expect to wait quite a while for computation of the result list to complete.
More informationCS 312. Lecture April Lazy Evaluation, Thunks, and Streams. Evaluation
CS 312 Lecture 27 29 April 2008 Lazy Evaluation, Thunks, and Streams Evaluation SML as you know it (substitution semantics) if true then e 1 else e 2 e 1 if false then e 1 else e 2 e 2 if eagerly evaluates
More informationLecture Notes on Induction and Recursion
Lecture Notes on Induction and Recursion 15-317: Constructive Logic Frank Pfenning Lecture 7 September 19, 2017 1 Introduction At this point in the course we have developed a good formal understanding
More informationCS115 - Module 8 - Binary trees
Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Section 14. Binary arithmetic expressions Operators such as +,,, and take two arguments, so we call them binary operators.
More informationn n Try tutorial on front page to get started! n spring13/ n Stack Overflow!
Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!
More informationCSC/MAT-220: Lab 6. Due: 11/26/2018
CSC/MAT-220: Lab 6 Due: 11/26/2018 In Lab 2 we discussed value and type bindings. Recall, value bindings bind a value to a variable and are intended to be static for the life of a program. Type bindings
More informationCOP4020 Programming Languages. Functional Programming Prof. Robert van Engelen
COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts
More informationModule 9: Binary trees
Module 9: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.
More informationFunctional Paradigm II
Processadors de Llenguatge II Functional Paradigm II Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra User-Defined Types How to define the new type.
More informationRecursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. Higher-Order Functions
CSE 130 : Programming Languages Higher-Order Functions Ranjit Jhala UC San Diego Recursion A way of life A different way to view computation Solutions for bigger problems From solutions for sub-problems
More information02157 Functional Programming Tagged values and Higher-order list functions
Tagged values and Higher-order list functions nsen 1 DTU Informatics, Technical University of Denmark Tagged values and Higher-order list functions MRH 27/09/2012 Part I: Disjoint Sets An Example A shape
More informationCSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013
CSE341: Programming Languages Lecture 7 First-Class Functions Dan Grossman Winter 2013 What is functional programming? Functional programming can mean a few different things: 1. Avoiding mutation in most/all
More informationCS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1
CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1 Goals of this tutorial You should be able to... understand
More informationList Processing in SML
CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College Consing Elements into Lists - val nums = 9 :: 4 :: 7 :: []; val nums = [9,4,7] : int list - 5 :: nums;
More informationFunctional Programming in Haskell Part I : Basics
Functional Programming in Haskell Part I : Basics Madhavan Mukund Chennai Mathematical Institute 92 G N Chetty Rd, Chennai 600 017, India madhavan@cmi.ac.in http://www.cmi.ac.in/ madhavan Madras Christian
More informationWrite: evens. evens [] ====> [] evens [1;2;3;4] ====> [2;4]
Write: evens (* val evens: int list -> int list *) let rec evens xs = [] ->... x::xs ->... evens [] ====> [] evens [1;2;3;4] ====> [2;4] Write: evens (* val evens: int list -> int list *) let rec evens
More informationHaskell Overview II (2A) Young Won Lim 9/26/16
(2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published
More informationCSC324 Functional Programming Typing, Exceptions in ML
CSC324 Functional Programming Typing, Exceptions in ML Afsaneh Fazly 1 Winter 2013 1 with many thanks to Anya Tafliovich, Gerald Penn, Sheila McIlraith, Wael Aboelsaddat, Tony Bonner, Eric Joanis, Suzanne
More informationHigher Order Functions in Haskell
Higher Order Functions in Haskell Evan Misshula 2018-09-10 Outline Curried Functions Curried comparison Example partial application partial application of a string function Returned functions ZipWith flip
More information02157 Functional Programming Lecture 1: Introduction and Getting Started
Lecture 1: Introduction and Getting Started nsen 1 DTU Informatics, Technical University of Denmark Lecture 1: Introduction and Getting Started MRH 6/09/2012 WELCOME to Teacher: nsen DTU Informatics, mrh@imm.dtu.dk
More informationCSE341 Spring 2016, Midterm Examination April 29, 2016
CSE341 Spring 2016, Midterm Examination April 29, 2016 Please do not turn the page until 10:30. Rules: The exam is closed-book, closed-note, etc. except for one side of one 8.5x11in piece of paper. Please
More informationModule 8: Binary trees
Module 8: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.
More informationList Processing in SML
List Processing in SML CS251 Programming Languages Spring 2017 Lyn Turbak, Meera Hejmadi, Mary Ruth Ngo, & Angela Wu Department of Computer Science Wellesley College Consing Elements into Lists - val nums
More informationCS 440: Programming Languages and Translators, Spring 2019 Mon
Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed
More informationStandard ML. Curried Functions. ML Curried Functions.1
Standard ML Curried Functions ML Curried Functions.1 Curried Functions Side Note: Infix function declaration o Curried Function declaration o Declaring via "fun" o Function Calling Order o Examples o Mixing
More informationFunctional Programming and Haskell
Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming
More informationProgramming Language Concepts, CS2104 Lecture 7
Reminder of Last Lecture Programming Language Concepts, CS2104 Lecture 7 Tupled Recursion Exceptions Types, ADT, Haskell, Components 5th Oct 2007 CS2104, Lecture 7 1 Overview 5th Oct 2007 CS2104, Lecture
More informationLists. Adrian Groza. Department of Computer Science Technical University of Cluj-Napoca
Lists Adrian Groza Department of Computer Science Technical University of Cluj-Napoca Recall... Parameter evaluation Call-by-value Call-by-name Call-by-need Functions Infix operators Local declarations,
More informationTuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example
CMSC 330: Organization of Programming Languages OCaml 2 Higher Order Functions Tuples Constructed using (e1,..., en) Deconstructed using pattern matching Patterns involve parens and commas, e.g., (p1,p2,
More informationAll the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)
Weekly exercises in INF3110 week 41 6-10.10.2008 Exercise 1 Exercise 6.1 in Mitchell's book a) fun a(x,y) = x+2*y; val a = fn : int * int -> int All the operations used in the expression are over integers.
More informationCOSE212: Programming Languages. Lecture 3 Functional Programming in OCaml
COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of
More informationCOSE212: Programming Languages. Lecture 4 Recursive and Higher-Order Programming
COSE212: Programming Languages Lecture 4 Recursive and Higher-Order Programming Hakjoo Oh 2016 Fall Hakjoo Oh COSE212 2016 Fall, Lecture 4 September 27, 2016 1 / 21 Recursive and Higher-Order Programming
More informationIntroduction to OCaml
Fall 2018 Introduction to OCaml Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl References Learn X in Y Minutes Ocaml Real World OCaml Cornell CS 3110 Spring 2018 Data Structures and Functional
More informationFall 2018 Lecture N
15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional
More information02157 Functional Programming. Michael R. Ha. Tagged values and Higher-order list functions. Michael R. Hansen
Tagged values and Higher-order list functions nsen 1 DTU Compute, Technical University of Denmark Tagged values and Higher-order list functions MRH 3/10/2017 Overview Disjoint union (or Tagged Values)
More informationCS 209 Functional Programming
CS 209 Functional Programming Lecture 03 - Intro to Monads Dr. Greg Lavender Department of Computer Science Stanford University "The most important thing in a programming language is the name. A language
More informationWatch out for the arrows. Recollecting Haskell, Part V. A start on higher types: Mapping, 1. A start on higher types: Mapping, 2.
Watch out for the arrows Recollecting Haskell, Part V Higher Types CIS 352/Spring 2018 Programming Languages January 30, 2018 1 / 28 2 / 28 A start on higher types: Mapping, 1 Mapping via list comprehension
More informationLecture 21: Functional Programming in Python. List Comprehensions
The University of North Carolina at Chapel Hill Spring 2002 Lecture 21: Functional Programming in March 1 1 List Comprehensions Haskell Lists can be defined by enumeration using list comprehensions Syntax:
More information