Cs3180 (Prasad)L156HOF1 Higher-Order Functions. cs3180 (Prasad)L156HOF2 Equivalent Notations (define (f x y) (… body …)) = (define f (lambda (x y) (…

Slides:



Advertisements
Similar presentations
1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
Advertisements

Programming Languages and Paradigms
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
Cs784(TK)1 Semantics of Procedures and Scopes. Kinds of Scope Static or Lexical scope –determined by structure of program –Scheme, C++, Java, and many.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
ISBN Chapter 9 Subprograms. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Introduction Two fundamental abstraction facilities.
Catriel Beeri Pls/Winter 2004/5 environment 68  Some details of implementation As part of / extension of type-checking: Each declaration d(x) associated.
Chapter 3 Program translation1 Chapt. 3 Language Translation Syntax and Semantics Translation phases Formal translation models.
The environment of the computation Declarations introduce names that denote entities. At execution-time, entities are bound to values or to locations:
1 Scheme Although Scheme is syntactically a simple language, it supports sophisticated modeling: higher-order functions are a powerful tool in describing.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
SchemeCOP Introduction to Scheme. SchemeCOP Scheme Meta-language for coding interpreters –“ clean ” semantics Scheme = LISP + ALGOL –simple.
Cs784(Prasad)L123Assg1 Assignments. cs784(Prasad)L123Assg2 l-value vs. r-value Pascal/Ada: x := x + 1 C/Java: x = x + 1 l-value = location, address, reference,
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Slide 1 Vitaly Shmatikov CS 345 Introduction to Scheme.
Names and Binding In procedural programming, you write instructions the manipulate the “state” of the process where the “state” is the collection of variables.
Functional Programming Universitatea Politehnica Bucuresti Adina Magda Florea
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Runtime Environments Compiler Construction Chapter 7.
Bindings and scope  Bindings and environments  Scope and block structure  Declarations Programming Languages 3 © 2012 David A Watt, University.
Cs7100(Prasad)L8Proc1 Procedures. cs7100(Prasad)L8Proc2 Primitive procedures  etc User-defined procedures –Naming a sequence of operations.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
Subprograms Support process abstraction and modularity –characteristics of subprograms are that they have a single entry point the calling entity is suspended.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CSC 580 – Theory of Programming Languages, Spring, 2009 Week 9: Functional Languages ML and Haskell, Dr. Dale E. Parson.
Basic Semantics Associating meaning with language entities.
Dr. Philip Cannata 1 Functions and Recursion. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython.
CSC3315 (Spring 2008)1 CSC 3315 Subprograms Hamid Harroud School of Science and Engineering, Akhawayn University
Functional Programming in Scheme and Lisp.
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
CSE 425: Control Abstraction I Functions vs. Procedures It is useful to differentiate functions vs. procedures –Procedures have side effects but usually.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
Programming Languages and Design Lecture 6 Names, Scopes and Binding Instructor: Li Ma Department of Computer Science Texas Southern University, Houston.
Programming Languages: Design, Specification, and Implementation G Rob Strom September 21, 2006.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Variables reference, coding, visibility. Rules for making names  permitted character set  maximum length, significant length  case sensitivity  special.
CSE 5317/4305 L12: Higher-Order Functions1 Functional Languages and Higher-Order Functions Leonidas Fegaras.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Names, Scope, and Bindings Programming Languages and Paradigms.
Ada, Scheme, R Emory Wingard. Ada History Department of Defense in search of high level language around Requirements drafted for the language.
Cs7120 (Prasad)L1-FP-HOF1 Functional Programming Basics Correctness > Clarity > Efficiency.
Cs776 (Prasad)L2HOF1 Higher-Order Functions. cs776 (Prasad)L2HOF2 Higher-Order Functions A function that takes a function as argument and/or returns a.
CSI 3125, Data Types, page 1 Data types Outline Primitive data types Structured data types Strings Enumerated types Arrays Records Pointers Reading assignment.
CS314 – Section 5 Recitation 9
Functional Programming
CS314 – Section 5 Recitation 10
Type Checking Generalizes the concept of operands and operators to include subprograms and assignments Type checking is the activity of ensuring that the.
6.001 SICP Object Oriented Programming
Introduction to Scheme
Principles of programming languages 4: Parameter passing, Scope rules
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Closures and Streams cs784(Prasad) L11Clos
Introduction to Functional Programming in Racket
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
FP Foundations, Scheme In Text: Chapter 14.
Dynamic Scoping Lazy Evaluation
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Bindings, Scope, and Extent
Introduction to Functional Programming in Racket
Closures and Streams cs7100(Prasad) L11Clos
CSE 341 Lecture 11 b closures; scoping rules
topics interpreters meta-linguistic abstraction eval and apply
More Scheme CS 331.
Presentation transcript:

cs3180 (Prasad)L156HOF1 Higher-Order Functions

cs3180 (Prasad)L156HOF2 Equivalent Notations (define (f x y) (… body …)) = (define f (lambda (x y) (… body …) ) )

cs3180 (Prasad)L156HOF3 Function Values (define tag (lambda (t l) (cons t l)) ) (tag ’int ’(1)) -> (int 1) What characterizes a function? –Expression in the body of the definition. –The sequence of formal parameters.

cs3180 (Prasad)L156HOF4 Anonymous Functions (lambda (t l) (cons t l)) ( (lambda (t l) (cons t l)) ’int ’(1) ) Name of the function is “irrelevant”. Simplification: (define tag cons) Assigning function values is similar to assigning primitive values. (first-class values).

cs3180 (Prasad)L156HOF5 Higher-order Functions In Scheme, function values can be –a) passed to other functions. –b) returned from functions. –c) stored in data structures. FORTRAN, Ada, etc prohibit a), b), c). Pascal allows only a). LISP/C++/Java support approximations in a round about way. –LISP : Meta-programming, C++: Function pointers. –Java : via Objects (Closures coming in JDK 7) Scala, Python and C# (delegates) are multi-paradigm languages with support for higher-order functions. ML/Scheme are functional languages that treat function values as first-class citizens. Implementing subprograms using a stack breaks down here. Heap and garbage collection required.

cs3180 (Prasad)L156HOF6 Applications Abstracting commonly occurring patterns of control. (factoring) Defining generic functions. Instantiating generics. ( ORTHOGONALITY ) –Eventually contribute to readability, reliability, and reuse. –Library: collection of higher-order functions.

cs3180 (Prasad)L156HOF7 Factoring Commonality (1 2 … n) -> (1 4 … n^2) (define (sql L) null (if (null? L) () cons (cons car (* (car L) car (car L) ) cdr (sql (cdr L)) ))) (a b c) -> ((a) (b) (c)) (define (brac L) null? (if (null? L) () cons (cons list (list car (car L) ) cdr (brac (cdr L)) )))

cs3180 (Prasad)L156HOF8 The map function (define (map fn lis) (if (null? lis) '() (cons (fn (car lis)) (map fn (cdr lis)) ) ) ) (map (lambda(x) (* x x)) '(1 2 3)) (map (lambda(x) (list x)) '(a b c)) Built-in map: (map + '(1 2 3) '(4 5 6)) = (5 7 9)

cs3180 (Prasad)L156HOF9 foldr (reduce) and foldl (accumulate) (Racket : > Intermediate Level) (foldr (list 2 4 8)) = = 114 (foldr cons '(c) '(a b)) = (a b c) (foldl * 100 (list 2 4 8)) = 8 * 4 * 2 * 100 = 6400 (foldl cons ' (c) '(a b)) = (b a c)

cs3180 (Prasad)L156HOF10 Templates/Generics (define (imax x y) (if (< x y) y x) ) (define (cmax x y) (if ( char-<? x y) y x ) ) Parameterize wrt comparison Generalization (define (max lt? x y) (if (lt? x y) y x) ) Specialization (max string-<? “a” “ab”) Passing function values

cs3180 (Prasad)L156HOF11 Instantiation (define (maxg lt?) (lambda (x y) (max lt? x y) ) ) ( (maxg >) 4 5 ) (* customization at run-time *) Function generating function. –Closure –Closure construction. Higher-order functions in a library may be tailored this way for different use.

Recursion vs Higher-Order Functions (define-struct cost ($)) make-costcost-$ ; generates code for make-cost & cost-$ (define costList make-costmake-cost (list (make-cost 5) (make-cost 10) make-cost (make-cost 25))) (check-expect (totalCost costList) 40) (check-expect (totalCost costList) (totalCostHF costList)) cs3180 (Prasad)L156HOF12

Simple Recursion vs Map-Reduce version (define (totalCost cl) (if (null? cl) 0 [+ (cost-$ (car cl)) (totalCost (cdr cl))] ) ) (define (totalCostHF cl) (foldr + 0 (map cost-$ cl))) Both foldl and foldr admissible. Requires DrRacket : > HtDP Intermediate Level cs3180 (Prasad)L156HOF13

Higher-Order Functions in Clojure (defn sumSqrNumList [ln] ( reduce + 0 (map #(* % %) ln) ) ) (sumSqrNumList '( )) ; 30 (map + '(1 2) '(3 4)) ; ( 4 6) (apply map (list + '(1 2) '(3 4)) cs3180 (Prasad)L156HOF14

cs3180 (Prasad)L156HOF15 Scoping use declarationRules governing the association of use of a variable with the corresponding declaration. proc p (x: int) ; proc q; var y: int; begin x := y end; begin q end; Local / non-localImperative Language : Local / non-local variables. Bound / freeFunctional Language : Bound / free variables.

cs3180 (Prasad)L156HOF16 Scoping rules enable determination of declaration corresponding to a non-local / free variable. Alternatives –Fixed at function definition time Static / lexical scoping –Scheme, Ada, C++, Java, C#, etc –Fixed at function call time Dynamic scoping –Franz LISP, APL, etc.

cs3180 (Prasad)L156HOF17 Pascal Example proc p; var z:int; proc q; begin z := 5 end; begin z := 5 end; proc r; var z:int; var z:int; begin q end; begin q end; proc s; var z:int; begin q end; begin … end;

cs3180 (Prasad)L156HOF18 Scoping : z ?? Staticr: z := 5; s:s: Calls to q in r and s update the variable z declared in p. Dynamicr: z := 5; z := 5; s: z := 5; r z Calls to q in r and s update the variables z and z declared in r and s respectively.

cs3180 (Prasad)L156HOF19 Scoping : functional style (define y 5) ( (lambda (x) (+ x y)) 3 ) –Point of definition = Point of call. (define (f x) (+ x y)) (define (g y) (f y)) (g 16) – Naming context of definition =/= Naming context of call.

Scoping Rules Static Scoping (g y) y <- 16 (f y) y <- 16 (+ x y) x <- 16 y < Dynamic Scoping (g y) y <- 16 (f y) y <- 16 (+ x y) x <- 16 y <- 16 y < cs3180 (Prasad)L156HOF20

cs3180 (Prasad)L156HOF21 (define (addn n) (lambda (x) (+ x n) ) ) (addn 5) = Closure Closure = Function Definition + Creation-time environment lexical scoping ( to enforce lexical scoping for free variables ) Closure (lambda (x) (+x n) ) n <- 5

cs3180 (Prasad)L156HOF22 Scoping in Clojure (def y 5) ( #(+ % y) 3 ) 8 (defn f [x] (+ x y)) (defn g [y] (f y)) (g 16) 21

cs3180 (Prasad)L156HOF23 Application Instantiating generic functions. Object-oriented Programming Using (1) let -construct (to introduce local variables) and (2) assignments, objects and classes can be simulated. Streams Creation of “infinite” data structures.

cs3180 (Prasad)L156HOF24 Lambda Expressions (define (id x) x) (define id (lambda (x) x) ) (lambda (x) x) ( (lambda (x) x) 5 ) (lambda () 5)

cs3180 (Prasad)L156HOF25 Lambda Expressions (lambda () 1) ( (lambda () 1) ) ( (lambda (x) x) (lambda (y) y) ) ( (lambda (x) (x x)) (lambda (y) y) )