Functional Programming - 2. Higher Order Functions

Similar documents
Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

User-defined Functions. Conditional Expressions in Scheme

CS 314 Principles of Programming Languages

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Random Testing in 321

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Functional Programming. Pure Functional Programming

CS 275 Name Final Exam Solutions December 16, 2016

Random Testing in 321

CSCC24 Functional Programming Scheme Part 2

Scheme Quick Reference

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CS 314 Principles of Programming Languages. Lecture 16

Scheme Quick Reference

A Brief Introduction to Scheme (II)

CS 314 Principles of Programming Languages

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Equivalent Notations. Higher-Order Functions. (define (f x y) ( body )) = (define f (lambda (x y) ) ) Anonymous Functions.

CITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Vectors in Scheme. Data Structures in Scheme

CS 314 Principles of Programming Languages

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

CS450 - Structure of Higher Level Languages

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Chapter 15 Functional Programming Languages

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Administrative Stuff

Functional Programming

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

FP Foundations, Scheme

Lecture 4: Higher Order Functions

Functional Programming

CS 340 Spring 2019 Midterm Exam

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Scheme as implemented by Racket

Building a system for symbolic differentiation

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

CSCE 314 Programming Languages

Shell CSCE 314 TAMU. Higher Order Functions

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

CS61A Midterm 2 Review (v1.1)

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

Scheme Basics > (butfirst '(help!)) ()

MoreIntro.v. MoreIntro.v. Printed by Zach Tatlock. Oct 07, 16 18:11 Page 1/10. Oct 07, 16 18:11 Page 2/10. Monday October 10, 2016 lec02/moreintro.

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Functions and Recursion. Dr. Philip Cannata 1

LECTURE 16. Functional Programming

(add1 3) 4 (check-expect (add1 3) 4)

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Lisp Basic Example Test Questions

Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018

Streams and Evalutation Strategies

Functional programming with Common Lisp

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

cs61amt2_4 CS 61A Midterm #2 ver March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

An introduction to Scheme

Box-and-arrow Diagrams

Chapter 15. Functional Programming Languages

The Typed Racket Guide

April 2 to April 4, 2018

CSc 520 Principles of Programming Languages

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Structure and Interpretation of Computer Programs

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

1.3. Conditional expressions To express case distinctions like

An Explicit-Continuation Metacircular Evaluator

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

From Templates to Folds

Building a system for symbolic differentiation

Homework 1. Reading. Problems. Handout 3 CSCI 334: Spring, 2012

CSE 341 Section Handout #6 Cheat Sheet

Chapter 1. Fundamentals of Higher Order Programming

Introduction to Functional Programming

MoreIntro_annotated.v. MoreIntro_annotated.v. Printed by Zach Tatlock. Oct 04, 16 21:55 Page 1/10

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

CS 440: Programming Languages and Translators, Spring 2019 Mon

Functions, Conditionals & Predicates

CS 320 Homework One Due 2/5 11:59pm

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

Transcription:

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 values Functions as arguments (define (f g x) (g x)) (f number? 0) yields #t (f len (1 (2 3)) ) yields 2 (f (lambda (x) (* 2 x)) 3) yields 6 Functions as return values (define incr (lambda (n) (+ 1 n)) ) (incr 1) returns 2, incr returns #procedure:incr Functional-11, CS5314, Sp16 BGRyder 2 1

Built-in function map Higher order function used to apply another function to every element of a list Takes 2 arguments: a function f and a list ys and builds a new list by applying the function to every element of the (argument) list (define (map f ys) (if (null? ys) ( ) (cons (f (car ys)) (map f (cdr ys)))))) Functional-11, CS5314, Sp16 BGRyder 3 Built-in function map (define (map f ys) (if (null? ys) ( ) (cons (f (car ys)) (map f (cdr ys)))))) (map incr (1 2 3 4)) returns (2 3 4 5) (map incr (-1 0 1)) returns (0 1 2) (map (lambda (x) (* 2 x)) (1 2 3)) returns (2 4 6) Possible to define a new map function map2 that takes n-ary functions and applies them to n lists, creating a new list (map2 + (1 2 3) (4 5 6)) returns (5 7 9) Functional-11, CS5314, Sp16 BGRyder 4 2

How map works? (define (map f ys) (if (null? ys) ( ) (cons (f (car ys)) (map f (cdr ys)))))) TRACE of execution: (map abs ( -1 2-3) (cons (abs -1) (map abs (2-3))) (cons (abs 2) (map abs (-3))) (cons (abs -3) (map abs ()) () (3) (2 3) (1 2 3) (list 1 2 3) Try stepping through the mapp definition in DrRacket. Functional-11, CS5314, Sp16 BGRyder 5 Using map Define atomcnt3 which uses map to calculate the number of atoms in a list. atomcnt3 creates a list of the count of atoms in every sublist and apply of + calculates the sublist sum. (define (atomcnt3 s) (cond ((atom? s) 1) (else (apply + (map atomcnt3 s))))) (atomcnt3 (1 2 3)) returns 3 (atomcnt3 ((a b) d)) returns 3 (atomcnt3 (1 ((2) 3) (((3) (2) 1)))) returns 6 How does this function work? Functional-11, CS5314, Sp16 BGRyder 6 3

apply apply is a built-in function whose first argument f is a function and whose second argument ys is a list of arguments for that function evaluation of apply applies f to ys (apply + (1 2 3)) returns 6 (apply zero? (2)) returns #false (apply zero? (0)) returns #true (apply (lambda (n) (+ 1 n)) (3)) returns 4 The power of apply is that it lets your program build an S-expression to evaluate during execution, and then lets it be evaluated. Functional-11, CS5314, Sp16 BGRyder 7 foldr Higher order function that takes a binary, associative operation and uses it to roll-up a list (define (foldr op ys id) (if (null? ys) id (op (car ys) (foldr op (cdr ys) id)) )) (foldr + (10 20 30) 0) yields (+ 10 (foldr + (20 30) 0) ) (+ 10 (+ 20 (foldr + (30) 0) )) (+ 10 (+ 20 (+ 30 (foldr + () 0)))) (+ 10 (+ 20 (+ 30 0))) yields 60 Think of inserting the op where the cons constructor is placed to build the list. Functional-11, CS5314, Sp16 BGRyder 8 4

The Power of Higher Order Functions Can compose higher order functions to form compact powerful functions (define (sum f ys) (foldr + (map f ys) 0)) sum takes a function f and a list ys sum applies f to each element of the list and then sums the results (sum (lambda (x) (* 2 x)) (1 2 3)) yields 12 (sum square (2 3)) yields 13 Functional-11, CS5314, Sp16 BGRyder 9 Using foldr (foldr append ((1 2) (3 4)) ( ) ) yields (app (list 1 2) (foldr append ((3 4)) ( ) ) ) (app (list 3 4) (foldr append ( ) ( ) )) ( ) (list 3 4) (list 1 2 3 4) Try this out using the stepper in DrRacket and watch how foldr works Ø (list 1 2 3 4) Defining len (list length function) from foldr. (define (len z) (foldr (lambda (x y) (+ 1 y)) z 0)) Functional-11, CS5314, Sp16 BGRyder 10 5

Informal Trace of len (len (5 6 7)) is (foldr (lambda (x y) (+ 1 y)) (5 6 7) 0)) ( (lambda (x y) (+ 1 y)) 5 (foldr (lambda (x y) (+ 1 y)) (6 7) 0) ) ( (lambda ) 6 (foldr (lamb ) (7) 0) ) ( (lamb.. 7 (foldr (lamb ) ( ) 0) ) 0 ( (lambda (x y) (+ 1 y)) 7 0) yields 1 ((lambda (x y) (+ 1 y)) 6 1) yields 2 ( (lambda (x y) (+ 1 y)) 5 2) yields 3 3 Functional-11, CS5314, Sp16 BGRyder 11 Fold operations Operations that combine elements of an S- expr in an ordered manner foldr - right associative (foldr + (1 2 3 ) 0) can see computation tree in which partial sums are calculated in order down the right branch (define (foldr op ys id) (if (null? ys) id (op (car ys) (foldr op (cdr ys) id)) )) 1 2 3 () 0 3 5 6 Functional-11, CS5314, Sp16 BGRyder 12 6

Fold operations foldl - left associative, more efficient than foldr (foldl + (1 2 3) 0) can see computation tree in which partial sums are calculated in order down the left branch Note foldl uses less storage than foldr, because doesn t need to keep values in the recursive copies; Instead it accumulates sum as it recurses downward (define (foldl g ys u) (if (null? ys) u (foldl g (cdr ys) (g u (car ys))))) 1 2 3 () 0 3 6 6 Functional-11, CS5314, Sp16 BGRyder 13 Using foldl (define (rev xs) (foldl (lambda (x y) (cons y x)) xs ())) then (rev (1 2 3)) will result in the following: order of execution: 1 2 3 (cons 1 ()) (1) (cons 2 (1)) (2 1) (cons 3 (2 1)) (3 2 1) (define (foldl g ys u) (if (null? ys) u (foldl g (cdr ys) (g u (car ys))))) Functional-11, CS5314, Sp16 BGRyder 14 7

Comparison of Fold Functions (define (foldr op ys id) (if (null? ys) id (op (car ys) (foldr op (cdr ys) id)) )) (define (foldl g ys u) (if (null? ys) u (foldl g (cdr ys) (g u (car ys))))) Compare underlined portions of these 2 functions Can see that foldl returns the value obtained from a recursive call to itself! Foldr contains a recursive call, but it is not the entire return value of the function Functional-11, CS5314, Sp16 BGRyder 15 Let expressions Let-expr ::= ( let ( Binding-list ) S-expr1 ) Let*-expr ::= ( let* ( Binding-list ) S-expr ) Binding-list ::= ( Var S-expr) { (Var S-expr) } Let and Let* expressions define a binding between each Var and the S-expr value, which holds during execution of S-expr1 Let evaluates the S-exprs in parallel (no order specified); Let* evaluates them from left to right. Both used to associate temporary values with variables for a local computation Variables declared in let s follow lexical scoping rules Functional-11, CS5314, Sp16 BGRyder 16 8

Let Examples (let ((x 2)) (* x x)) yields 4 (let ((x 2)) (let ((y 1)) (+ x y) ) ) yields 3 (let ((x 10) (y (* 2 x))) (* x y)) is an error because all exprs evaluated in parallel and simultaneously bound to the vars (let* ((x 10) (y (* 2 x))) (* x y)) yields 200 Functional-11, CS5314, Sp16 BGRyder 17 Let Examples (let ((x 10)) ; causes x to be bound to 10 (let ((f (lambda (a) (+ a x)))) ;causes f to bound to the lambda expr (let ((x 2)) (f 5) ) ) ) Evaluation yields (+ 5 10) = 15, NOT (+ 5 2) = 7 In dynamic scoping the answer would be 7! (define (f z) (let* ((x 5) (f (lambda (z) (* x z)))) (map f z))) What does this function do? Functional-11, CS5314, Sp16 BGRyder 18 9