Factorial. Next. Factorial. How does it execute? Tail recursion. How does it execute? More on recursion. Higherorder functions


 Britton Holland
 2 years ago
 Views:
Transcription
1 Next More on recursion Higherorder functions takg and returng functions Factorial let rec fact n = Along the way, will see map and fold 1 2 Factorial let rec fact n = if n<=0 then 1 else n * fact (n1);; How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n1);; fac 3;; 3 4 How does it execute? let rec fact n = if n<=0 then 1 else n * fact (n1);; fac 3;; Tail recursion Tail recursion: recursion where all recursive calls are followed by a return other words: not allowed to do any between recursive call and return 5 6 1
2 Tail recursive factorial Tail recursive factorial let rec helper x curr = if x <= 0 then curr else helper (x  1) (x * curr) helper x 1;; 7 8 How does it execute? How does it execute? let rec helper x curr = if x <= 0 then curr else helper (x  1) (x * curr) helper x 1;; fact 3;; let rec helper x curr = if x <= 0 then curr else helper (x  1) (x * curr) helper x 1;; fact 3;; 9 10 Tail recursion Compiler can optimize! Tail recursion: recursion where all recursive calls are followed by a return other words: not allowed to do anythg between recursive call and return let rec helper x curr = if x <= 0 then curr else helper (x  1) (x * curr) fact(x) { curr := 1; while (1) { if (x <= 0) then { return curr } else { x := x 1; curr := (x * curr) } Why do we care about tail recursion? it turns out that tail recursion can be optimized to a simple loop 11 helper x 1;; recursion! } Loop! 12 2
3 Tail recursion summary Tail recursive calls can be optimized as a jump Part of the language specification of some languages (ie: you can count on the compiler to optimize tail recursive calls) max function let max x y = if x < y then y else x;; (* return max element of list l *) let list_max l = max function concat function let max x y = if x < y then y else x;; (* return max element of list l *) let list_max l = h::t > helper (max h curr) t helper 0 l;; 15 (* concatenate all strgs a list *) let concat l = 16 concat function What s the pattern? (* concatenate all strgs a list *) let concat l = h::t > helper (curr ^ h) t helper "" l;; 17 let list_max l = h::t > helper (max h curr) t helper 0 l;; let concat l = h::t > helper (curr ^ h) t helper "" l;; 18 3
4 fold, the general helper func! (* to help us see the pattern: *) let list_max l = h::t > helper (max h curr) t helper 0 l;; fold (* fold, the coolest function there is! *) let rec fold f curr l = h::t > fold f (f h curr) t;; (* fold, the coolest function there is! *) let rec fold f curr l = fold Examples of fold (* fold, the coolest function there is! *) let rec fold f curr l = h::t > fold f (f h curr) t;; let list_max = let concat = let multiplier = Examples of fold Examples of fold let list_max = fold max 0;; let concat = fold (^) "";; let fact n = multiplier (terval 1 n);; Notice how all the recursion is buried side two functions: terval and fold! let multiplier = fold (*) 1;;
5 Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) Examples of fold let cons x y = x::y;; let f = fold cons [];; (* same as: let f l = fold cons [] l *) More recursion: terval terval (* return a list that contas the tegers i through j clusive *) let rec terval i j = (* return a list that contas the tegers i through j clusive *) let rec terval i j = if i > j then [] else i::(terval (i+1) j);; terval function with it fn terval function with it fn (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = (* return a list that contas the elements f(i), f(i+1),... f(j) *) let rec terval_it i j f = if i > j then [] else (f i)::(terval_it (i+1) j f);;
6 terval function aga terval function aga (* our regular terval function terms of the one with the it function *) let rec terval i j = (* our regular terval function terms of the one with the it function *) let rec terval i j = terval_it i j (fun x > x);; Interval function yet aga! Function Curryg (* let's change the order of parameters... *) let rec terval_it f i j = if i > j then [] else (f i)::(terval_it f (i+1) j);; (* now can use curryg to get terval function! *) let terval = terval_it (fun x > x);; 33 In general, these two are equivalent: let f = fun x1 > > fun xn > e let f x1 xn = e Multiple argument functions by returng a function that takes the next argument Named after a person (Haskell Curry) 34 Function Curryg vs tuples Function Curryg vs tuples Tuple version: fn defition let f (x1,,xn) = e fn call f (x1,,xn) Consider the followg: let lt x y = x < y; Curried version: fn defition let f x1 xn = e fn call f x1 xn 35 Could have done: let lt (x,y) = x<y; But then no testers possible In general: Curryg allows you to set just the first n params (where n smaller than the total number of params) 36 6
7 map map (* return the list contag f(e) for each element e of l *) let rec map f l = (* return the list contag f(e) for each element e of l *) let rec map f l = [] > [] h::t > (f h)::(map f t);; map let cr x = x+1;; let map_cr = map cr;; map_cr (terval (10) 10);; composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = composg functions (f o g) (x) = f(g(x)) (* return a function that given an argument x applies f2 to x and then applies f1 to the result*) let compose f1 f2 = fun x > (f1 (f2 x));; (* another way of writg it *) let compose f1 f2 x = f1 (f2 x);; Higherorder functions! let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (10) 10);; (compose map_cr_3 pos_filer) (terval (10) 10);;
8 Higherorder functions! Exercise 1 let map_cr_2 = compose map_cr map_cr;; map_cr_2 (terval (10) 10);; let map_cr_3 = compose map_cr map_cr_2;; map_cr_3 (terval (10) 10);; let map_cr_3_pos = compose pos_filer map_cr_3;; map_cr_3_pos (terval (10) 10);; (compose map_cr_3 pos_filer) (terval (10) 10);; Instead of manipulatg lists, we are let rec filter f l = [] > [] h::t > let t = filter f t if f h then h::t else t let neg f x = not (f x) let partition f l = (filter f l, filter (neg f) l) This implementation is not ideal, sce it unnecessarily processes the list twice. Rewrite partition so that it is a sgle call to fold_left, so the put list is processed only once. Recall: manipulatg the list manipulators! 43 val fold_left : ('a > 'b > 'a) > 'a > 'b list > 'a 44 Exercise 1 Solution val fold_left : ('a > 'b > 'a) > 'a > 'b list > 'a let partition f l = Exercise 1 Solution val fold_left : ('a > 'b > 'a) > 'a > 'b list > 'a let partition f l = let fold_fn (pass,passnot) x = if f x then passnot) else (pass, List.fold_left fold_fn ([],[]) l;; Exercise 2 val fold_left : ('a > 'b > 'a) > 'a > 'b list > 'a val map : ('a > 'b) > 'a list > 'b list Exercise 2 Solution val fold_left : ('a > 'b > 'a) > 'a > 'b list > 'a val map : ('a > 'b) > 'a list > 'b list Implement map usg fold: let map f l = Implement map usg fold: let map f l = List.fold_left (fun acc x > x]) [] l
9 Benefits of higherorder functions Identify common computation patterns Iterate a function over a set, list, tree Accumulate some value over a collection Funcs takg/returng funcs Higherorder funcs enable modular code Each part only needs local formation Data Structure Client Uses list Data Structure Library list Pull out (factor) common code: Computation Patterns Reuse many different situations 49 Uses metafunctions: map,fold,filter With locallydependent funs (lt h), square etc. Without requirg Implement. details of data structure Provides metafunctions: map,fold,filter to traverse, accumulate over lists, trees etc. Metafunctions don t need client fo 50 Different way of thkg Free your md Morpheus Different way of thkg about computation Manipulate the manipulators 51 9
Next. Tail Recursion: Factorial. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial.
Next Tail Recursion: Factorial More on recursion Higherorder functions takg and returng functions Along the way, will see map and fold let rec fact n = if n
More informationToday. Recap from last Week. Factorial. Factorial. How does it execute? How does it execute? More on recursion. Higherorder functions
Recap from last Week Three key ways to build complex types/values 1. Eachof types Value of T contas value of T1 and a value of T2 2. Oneof types Value of T contas value of T1 or a value of T2 Today More
More informationmax function Next concat function max function What s the pattern? concat function More on recursion Higherorder functions
Next More on recursion Higherorder functions taking and returning functions max function let max x y = if x < y then y else x;; (* return max element of list l *) Along the way, will see map and fold
More informationToday s Plan. Programming Languages. Example : Factorial. Recursion. CSE 130 : Spring Lecture 6: HigherOrder Functions
CSE 130 : Spring 2011 Programming Languages Lecture 6: HigherOrder Ranjit Jhala UC San Diego Today s Plan A little more practice with recursion Base Pattern > Base Expression Induction Pattern > Induction
More informationProgramming Languages. Tail Recursion. CSE 130: Winter Lecture 8: NOT TR. last thing function does is a recursive call
CSE 130: Winter 2010 News Programming Languages Lecture 8: HigherOrder Od Functions Ranjit Jhala UC San Diego Today s Plan Finish Static Scoping Tail Recursion last thing function does is a recursive
More informationRecap: Functions as firstclass values
Recap: Functions as firstclass values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse
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 informationRecursion. Q: What does this evaluate to? Q: What does this evaluate to? CSE 130 : Programming Languages. HigherOrder Functions
CSE 130 : Programming Languages HigherOrder Functions Ranjit Jhala UC San Diego Recursion A way of life A different way to view computation Solutions for bigger problems From solutions for subproblems
More informationNews. CSE 130: Programming Languages. Environments & Closures. Functions are firstclass values. Recap: Functions as firstclass values
CSE 130: Programming Languages Environments & Closures News PA 3 due THIS Friday (5/1) Midterm NEXT Friday (5/8) Ranjit Jhala UC San Diego Recap: Functions as firstclass values Arguments, return values,
More informationCSE 130 [Winter 2014] Programming Languages
CSE 130 [Winter 2014] Programming Languages HigherOrder Functions! Ravi Chugh! Jan 23 Today s Plan A little more practice with recursion Base Pattern Base Expression Induction Pattern Induction Expression
More informationCMSC 330: Organization of Programming Languages. OCaml Higher Order Functions
CMSC 330: Organization of Programming Languages OCaml Higher Order Functions CMSC330 Fall 2017 1 Anonymous Functions Recall code blocks in Ruby (1..10).each { x print x } Here, we can think of { x print
More informationCMSC 330: Organization of Programming Languages. OCaml Higher Order Functions
CMSC 330: Organization of Programming Languages OCaml Higher Order Functions CMSC 330  Spring 2017 1 Anonymous Functions Recall code blocks in Ruby (1..10).each { x print x } Here, we can think of { x
More informationCMSC 330: Organization of Programming Languages. OCaml Higher Order Functions
CMSC 330: Organization of Programming Languages OCaml Higher Order Functions CMSC 330  Summer 2017 1 Anonymous Functions Recall code blocks in Ruby (1..10).each { x print x } Here, we can think of { x
More informationFunctions Over Lists. Programming Languages and Compilers (CS 421) Structural Recursion. Functions Over Lists. Structural Recursion : List Example
Functions Over Lists Programmg Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illois.edu/cs421 Based part on slides by Mattox Beckman, as updated by Vikram Adve and Gul
More informationCSci 4223 Principles of Programming Languages
Review CSci 4223 Prciples of Programmg Languages Lecture 8 Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matchg, exceptions
More informationCMSC 330, Fall 2013, Practice Problems 3
CMSC 330, Fall 2013, Practice Problems 3 1. OCaml and Functional Programming a. Define functional programming b. Define imperative programming c. Define higherorder functions d. Describe the relationship
More informationCS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey
CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No
More informationBegin at the beginning
Begin at the beginning Expressions (Syntax) Exectime Dynamic Values (Semantics) Compiletime Static Types 1. Programmer enters expression 2. ML checks if expression is welltyped Using a precise set of
More informationCMSC 330, Fall 2013, Practice Problem 3 Solutions
CMSC 330, Fall 2013, Practice Problem 3 Solutions 1. OCaml and Functional Programming a. Define functional programming Programs are expression evaluations b. Define imperative programming Programs change
More informationFunctional Programming. Pure Functional Programming
Functional Programming With examples in F# Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands. Computation is largely performed by applying
More information# true;;  : bool = true. # false;;  : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4
Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;;  : bool = true # false;;  : bool
More informationBooleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and ShortCircuit Evaluation. Tuples as Values.
Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d # true;;  : bool = true # false;;  : bool =
More informationCS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey
CS 3110 Lecture 6: Map and Fold Prof. Clarkson Fall 2014 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Features so far: variables, operators, let expressions, if expressions,
More informationSCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))
SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 +  4 00 scm> (if
More informationMap and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey
Map and Fold Prof. Clarkson Fall 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Question How much progress have you made on A1? A. I'm still figuring out how Enigma works.
More informationTail Recursion: Factorial. Begin at the beginning. How does it execute? Tail recursion. Tail recursive factorial. Tail recursive factorial
Begin at the beginning Epressions (Synta) Compiletime Static Eectime Dynamic Types Values (Semantics) 1. Programmer enters epression 2. ML checks if epression is welltyped Using a precise set of rules,
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationOCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.
OCaml The PL for the discerning hacker. ML Flow Expressions (Syntax) Compiletime Static 1. Enter expression 2. ML infers a type Exectime Dynamic Types 3. ML crunches expression down to a value 4. Value
More informationFUNCTIONAL PROGRAMMING
FUNCTIONAL PROGRAMMING Map, Fold, and MapReduce Prof. Clarkson Summer 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Yesterday: Lists: OCaml's awesome builtin datatype
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 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 informationCS 312, Fall Exam 1
Name: ID number: CS 312, Fall 2003 Exam 1 October 16, 2003 Problem 1 2 3 4 Total Grader Grade 18 24 28 30 There are 4 problems on this exam. Please check now that you have a complete exam booklet with
More informationProgramming Languages and Compilers (CS 421)
Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illinois.edu/cs421 Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul Agha 9/11/17
More informationPlan (next 4 weeks) 1. Fast forward. 2. Rewind. 3. Slow motion. Rapid introduction to what s in OCaml. Go over the pieces individually
Plan (next 4 weeks) 1. Fast forward Rapid introduction to what s in OCaml 2. Rewind 3. Slow motion Go over the pieces individually History, Variants Meta Language Designed by Robin Milner @ Edinburgh Language
More informationA brief tour of history
Introducing Racket λ A brief tour of history We wanted a language that allowed symbolic manipulation Scheme The key to understanding LISP is understanding SExpressions Racket List of either atoms or
More informationMonday Feb 16, 5pm. solve these equalities. Midterm Thursday Feb 12. covers only ocaml part of the course, assignments 1 through 3.
News Programming Assignment 4 is up, due Monday Feb 16, 5pm Long assignment, start early Midterm Thursday Feb 12 covers only ocaml part of the course, assignments 1 through 3. Recap: Inferring types Introduce
More informationCSE341 Section 3. StandardLibrary Docs, FirstClass Functions, & More
CSE341 Section 3 StandardLibrary Docs, FirstClass Functions, & More Adapted from slides by Daniel Snitkovskiy, Nick Mooney, Nicholas Shahan, Patrick Larson, and Dan Grossman Agenda 1. SML Docs Standard
More informationCOP5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON RPAL
COP5555 PROGRAMMING LANGUAGEPRINCIPLES NOTES ON 1. Introduction is a subset of PAL, the Pedagogic Algorithmic Language. There are three versions of PAL:, LPAL, and JPAL. The only one of terest here is.
More informationCS 321 Programming Languages
CS 321 Programming Languages Intro to OCaml Lists Baris Aktemur Özyeğin University Last update made on Monday 2 nd October, 2017 at 19:27. Some of the contents here are taken from Elsa Gunter and Sam Kamin
More information15451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018
15451/651: Design & Analysis of Algorithms November 20, 2018 Lecture #23: Closest Pairs last changed: November 13, 2018 1 Prelimaries We ll give two algorithms for the followg closest pair problem: Given
More informationCOSE212: Programming Languages. Lecture 4 Recursive and HigherOrder Programming
COSE212: Programming Languages Lecture 4 Recursive and HigherOrder Programming Hakjoo Oh 2016 Fall Hakjoo Oh COSE212 2016 Fall, Lecture 4 September 27, 2016 1 / 21 Recursive and HigherOrder Programming
More informationINF121: Functional Algorithmic and Programming
INF121: Functional Algorithmic and Programming Lecture 6: Polymorphism, Higherorder, and Currying Academic Year 20112012 In the previous episodes of INF 121 Basic Types: Booleans, Integers, Floats, Chars,
More information15451/651: Design & Analysis of Algorithms April 18, 2016 Lecture #25 Closest Pairs last changed: April 18, 2016
15451/651: Design & Analysis of Algorithms April 18, 2016 Lecture #25 Closest Pairs last changed: April 18, 2016 1 Prelimaries We ll give two algorithms for the followg closest pair proglem: Given n pots
More informationOCaml. History, Variants. ML s holy trinity. Interacting with ML. Base type: Integers. Base type: Strings. *Notes from Sorin Lerner at UCSD*
OCaml 1. Introduction Rapid introduction to what s in OCaml 2. Focus on Features Individually as Needed as Semester Progresses *Notes from Sorin Lerner at UCSD* History, Variants Meta Language Designed
More informationBack to OCaml. Summary of polymorphism. Example 1. Type inference. Example 2. Example 2. Subtype. Polymorphic types allow us to reuse code.
Summary of polymorphism Subtype Parametric Bounded Fbounded Back to OCaml Polymorphic types allow us to reuse code However, not always obvious from staring at code But... Types never entered w/ program!
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 informationNews. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012
News CSE 130: Spring 2012 Programming Languages On webpage: Suggested HW #1 PA #1 (due next Fri 4/13) Lecture 2: A Crash Course in ML Please post questions to Piazza Ranjit Jhala UC San Diego Today: A
More informationCallbyname evaluation
Lecture IX Keywords: callbyvalue, callbyname, and callbyneed evaluation; lazy datatypes: sequences, streams, trees; lazy evaluation; sieve of Eratosthenes; breadthfirst and depthfirst traversals.
More informationRecap from last time. Programming Languages. CSE 130 : Fall Lecture 3: Data Types. Put it together: a filter function
CSE 130 : Fall 2011 Recap from last time Programming Languages Lecture 3: Data Types Ranjit Jhala UC San Diego 1 2 A shorthand for function binding Put it together: a filter function # let neg = fun f
More informationForward Recursion. Programming Languages and Compilers (CS 421) Mapping Recursion. Forward Recursion: Examples. Folding Recursion.
Forward Recursion Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://www.cs.uiuc.edu/class/cs421/ Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul
More informationProgramming Languages
CSE 130: Spring 2010 Programming Languages Lecture 3: Epressions and Types Ranjit Jhala UC San Diego A Problem fun > +1 Can functions only have a single parameter? A Solution: Simultaneous Binding Parameter
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 informationForward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack
Forward recursion CS 321 Programming Languages Intro to OCaml Recursion (tail vs forward) Baris Aktemur Özyeğin University Last update made on Thursday 12 th October, 2017 at 11:25. Much of the contents
More information7.3.3 A Language With Nested Procedure Declarations
7.3. ACCESS TO NONLOCAL DATA ON THE STACK 443 7.3.3 A Language With Nested Procedure Declarations The C family of languages, and many other familiar languages do not support nested procedures, so we troduce
More informationPlaying with Fun. Walter Cazzola. Playing with Fun currying partial evaluation map&reduce iteration var args. References.
Currying & Partial Evaluation Currying with Currying, MapFilter & Reduce, Folding,... with Currying is a technique to transform a function with multiple arguments into a chain of functions each with a
More informationVariables and Bindings
Net: Variables Variables and Bindings Q: How to use variables in ML? Q: How to assign to a variable? # let = 2+2;; val : int = 4 let = e;; Bind the value of epression e to the variable Variables and Bindings
More informationPROGRAMMING IN HASKELL. CS Chapter 6  Recursive Functions
PROGRAMMING IN HASKELL CS205  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 informationA Crash Course on Standard ML
A Crash Course on Standard ML Hongwei Xi Version of November 23, 2004 1 Start Type smlcm at a Unix wdow to get an teractive terpreter for Standard ML (SML). You can later quit the terpreter by typg ctrld.
More informationProgramming Languages
CSE 130 : Spring 2011 Programming Languages Lecture 3: Crash Course Ctd, Expressions and Types Ranjit Jhala UC San Diego A shorthand for function binding # let neg = fun f > fun x > not (f x); # let
More informationCSCI 2041: First Class Functions
CSCI 2041: First Class Functions Chris Kauffman Last Updated: Thu Oct 18 22:42:48 CDT 2018 1 Logistics Assignment 3 multimanager Reading OCaml System Manual: Ch 26: List and Array Modules, higherorder
More informationCSCIGA Scripting Languages
CSCIGA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation
More informationCurrying fun f x y = expression;
Currying ML chooses the most general (leastrestrictive) type possible for userdefined functions. Functions are firstclass objects, as in Scheme. The function definition fun f x y = expression; defines
More informationRedefinition of an identifier is OK, but this is redefinition not assignment; Thus
Redefinition of an identifier is OK, but this is redefinition not assignment; Thus val x = 100; val x = (x=100); is fine; there is no type error even though the first x is an integer and then it is a boolean.
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 informationSo what does studying PL buy me?
So what does studying PL buy me? Enables you to better choose the right language but isn t that decided by libraries, standards, and my boss? Yes. Chickenandegg. My goal: educate tomorrow s tech leaders
More informationAny questions. Say hello to OCaml. Say hello to OCaml. Why readability matters. History, Variants. Plan (next 4 weeks)
Any questions Say hello to OCaml? void sort(int arr[], int beg, int end){ if (end > beg + 1){ int piv = arr[beg]; int l = beg + 1; int r = end; while (l!= r1){ if(arr[l]
More informationCSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp
CSE 341 Lecture 5 efficiency issues; tail recursion; print Ullman 3.33.4; 4.1 slides created by Marty Stepp http://www.cs.washington.edu/341/ Efficiency exercise Write a function called reverse that accepts
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its subexpressions (if any).
More informationProgramming Languages
CSE 130 : Fall 2008 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1, sample for Quiz #1 on Thu PA #1 (due next Fri 10/10) No makeup quizzes
More informationCS1 Recitation. Week 2
CS1 Recitation Week 2 Sum of Squares Write a function that takes an integer n n must be at least 0 Function returns the sum of the square of each value between 0 and n, inclusive Code: (define (square
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 informationCMSC330 Spring 2014 Midterm 2 Solutions
CMSC330 Spring 2014 Midterm 2 Solutions 1. (16 pts) OCaml Types and Type Inference Give the type of the following OCaml expressions: a. (2 pts) fun b > b + 8 Type = int > int b. (3 pts) fun b > b 8
More informationCS422  Programming Language Design
1 CS422  Programming Language Design ContinuationPassing Style (CPS) Transformation Grigore Roşu Department of Computer Science University of Illinois at UrbanaChampaign 2 On Data Versus Control Context
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques () Lecture 9 January 31, 2018 Lists and Higherorder functions Lecture notes: Chapter 9 What is the type of this expresssion? [ (fun (x:int) > x + 1); (fun (x:int)
More informationProgramming Languages
CSE 130: Spring 2010 Programming Languages Lecture 2: A Crash Course in ML Ranjit Jhala UC San Diego News On webpage: Suggested HW #1 PA #1 (due next Wed 4/9) Please post questions to WebCT Today: A crash
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 informationHaske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell
Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program
More informationCS115  Module 9  filter, map, and friends
Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 1923. Abstraction abstraction, n. 3a.... The process of isolating properties or
More informationProgramming Languages
CSE 130 : Fall 2008 Programmg Languages Lecture 4: Variables, Environments, Scope News PA 1 due Frida 5pm PA 2 out esterda (due net Fi) Fri) Ranjit Jhala UC San Diego Variables and Bdgs Q: How to use variables
More informationCSE341: Programming Languages Lecture 9 FunctionClosure Idioms. Dan Grossman Winter 2013
CSE341: Programming Languages Lecture 9 FunctionClosure 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 wideranging
More informationCMSC330 Fall 2014 Midterm 2 Solutions
CMSC330 Fall 2014 Midterm 2 Solutions 1. (5 pts) General. For the following multiple choice questions, circle the letter(s) on the right corresponding to the best answer(s) to each question. a. In the
More informationLECTURE 16. Functional Programming
LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative
More informationAn introduction introduction to functional functional programming programming using usin Haskell
An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program
More informationHomework 5. Notes. TurnIn Instructions. Reading. Problems. Handout 19 CSCI 334: Spring (Required) Read Mitchell, Chapters 6 and 7.
Homework 5 Due Wednesday, 14 March Handout 19 CSCI 334: Spring 2018 Notes This homework has two types of problems: Problems: You will turn in answers to these questions. Pair Programming: This part involves
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 builtin ML type constructor. However, to introduce
More informationGain familiarity and practice with folding and mapping. The following supplementary materials may be helpful in completing this assignment:
CS 3110 Spring 2017 Problem Set 2 Version 1 (last modified February 23, 2017) Overview This assignment reinforces the use of recursion when approaching certain types of problems. We will emphasize the
More information15 212: Principles of Programming. Some Notes on Continuations
15 212: Principles of Programming Some Notes on Continuations Michael Erdmann Spring 2011 These notes provide a brief introduction to continuations as a programming technique. Continuations have a rich
More informationCMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm
CMSC330 Fall 2016 Midterm #1 2:00pm/3:30pm Name: Discussion Time: 10am 11am 12pm 1pm 2pm 3pm TA Name (Circle): Alex Austin Ayman Brian Damien Daniel K. Daniel P. Greg Tammy Tim Vitung Will K. Instructions
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 informationLecture 10: Recursion vs Iteration
cs2010: algorithms and data structures Lecture 10: Recursion vs Iteration Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin how methods execute Call stack: is a stack
More information1 Announcements. 2 Scan Implementation Recap. Recitation 4 Scan, Reduction, MapCollectReduce
Recitation 4 Scan, Reduction, MapCollectReduce Parallel and Sequential Data Structures and Algorithms, 15210 (Sprg 2013) February 6, 2013 1 Announcements How did HW 2 go? HW 3 is out get an early start!
More informationFinal Exam CSCI 1101 Computer Science I KEY. Wednesday December 16, 2015 Instructor Muller Boston College. Fall 2015
Fal Exam CSCI 1101 Computer Science I KEY Wednesday December 16, 2015 Instructor Muller Boston College Fall 2015 Please do not write your name on the top of this test. Before readg further, please arrange
More informationProgramming Languages
CSE 130: Fall 2009 Programming Languages Lecture 2: A Crash Course in ML News On webpage: Suggested HW #1 PA #1 (due next Fri 10/9) Technical issues installing Ocaml  should be resolved soon! Ranjit Jhala
More informationThis lecture covers: Prolog s execution strategy explained more precisely. Revision of the elementary Prolog data types
This lecture covers: Prolog s execution strategy explained more precisely The execution strategy has been presented as simply placing all matching clauses onto the stack. In fact, Prolog is slightly more
More informationIntroduction to Functional Programming and Haskell. Aden Seaman
Introduction to Functional Programming and Haskell Aden Seaman Functional Programming Functional Programming First Class Functions Expressions (No Assignment) (Ideally) No Side Effects Different Approach
More informationCMSC 330: Organization of Programming Languages. Closures (Implementing Higher Order Functions)
CMSC 330: Organization of Programming Languages Closures (Implementing Higher Order Functions) CMSC 330  Summer 2017 1 Returning Functions as Results In OCaml you can pass functions as arguments to map,
More informationConversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";
More informationInformatics 1 Functional Programming Lecture 7. Map, filter, fold. Don Sannella University of Edinburgh
Informatics 1 Functional Programming Lecture 7 Map, filter, fold Don Sannella University of Edinburgh Part I Map Squares *Main> squares [1,2,3] [1,4,9] squares :: [Int] > [Int] squares xs [ x*x x
More informationLecture #23: Conversion and Type Inference
Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:
More informationF#  LISTS. In this method, you just specify a semicolondelimited sequence of values in square brackets. For example
http://www.tutorialspoint.com/fsharp/fsharp_lists.htm F#  LISTS Copyright tutorialspoint.com In F#, a list is an ordered, immutable series of elements of the same type. It is to some extent equivalent
More information