# Functional Programming - 2. Higher Order Functions

Size: px
Start display at page:

Transcription

1 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

2 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 ( )) returns ( ) (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

3 How map works? (define (map f ys) (if (null? ys) ( ) (cons (f (car ys)) (map f (cdr ys)))))) TRACE of execution: (map abs ( ) (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

4 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 + ( ) 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

5 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 ) Try this out using the stepper in DrRacket and watch how foldr works Ø (list ) 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

6 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)) )) () Functional-11, CS5314, Sp16 BGRyder 12 6

7 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))))) () 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: (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

8 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

9 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

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

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

### User-defined Functions. Conditional Expressions in Scheme

User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 18: Functional Programming Zheng (Eddy) Zhang Rutgers University April 9, 2018 Review: Defining Scheme Functions (define ( lambda (

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

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

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

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

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

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

CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Summer 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,

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

CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 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

### Random Testing in 321

Random Testing in 321 1 Test Cases So Far Each test relates a particular input to a particular output. (test (bound-ids (with 'x (id 'y) (id 'x))) '(x)) (test (binding-ids (with 'x (id 'y) (id 'x))) '(x))

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

CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

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

SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 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,

### Functional 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 sub-expressions (if any).

### CS 275 Name Final Exam Solutions December 16, 2016

CS 275 Name Final Exam Solutions December 16, 2016 You may assume that atom? is a primitive procedure; you don t need to define it. Other helper functions that aren t a standard part of Scheme you need

### Random Testing in 321

Random Testing in 321 1 Test Cases So Far Each test relates a particular input to a particular output. (test (bound-ids (with 'x (id 'y) (id 'x))) '(x)) (test (binding-ids (with 'x (id 'y) (id 'x))) '(x))

### CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

### COP4020 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

### CS 314 Principles of Programming Languages. Lecture 16

CS 314 Principles of Programming Languages Lecture 16 Zheng Zhang Department of Computer Science Rutgers University Friday 28 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

### A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases

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

Introduction to Functional Programming in Racket CS 550 Programming Languages Jeremy Johnson 1 Objective To introduce functional programming in racket Programs are functions and their semantics involve

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

Equivalent Notations Higher-Order Functions cs480 (Prasad L156HOF 1 (define (f x y ( body = (define f (lambda (x y ( body cs480 (Prasad L156HOF 2 Function Values (define tag (lambda (t l (cons t l (tag

### CITS3211 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

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

SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 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,

### Vectors in Scheme. Data Structures in Scheme

Data Structures in Scheme Vectors in Scheme In Scheme, lists and S-expressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

### 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?

More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

### CS450 - Structure of Higher Level Languages

Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.

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

CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.

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

Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

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

The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

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

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

Administrative Stuff Use the new version of PLAI from planet. It will download the first time you run a program with the 7, like this: #lang planet plai/plai:1:7 This lets you ignore passing test cases

### Functional Programming

Functional Programming CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario When the Function is the Thing In O-O programming, you typically know where an action is needed,

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

CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp http://www.cs.washington.edu/341/ Lists (list expr2... exprn) '(value1 value2...

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

CS 61A, Fall, 2002, Midterm #2, L. Rowe 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams. a) d) 3 1 2 3 1 2 e) b) 3 c) 1 2 3 1 2 1 2 For each of the following Scheme

### FP Foundations, Scheme

FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

### Lecture 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

### Functional Programming

Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

### CS 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 SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

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

Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+

### Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

### Building a system for symbolic differentiation

Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

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

CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

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

SCHEME COMPUTER SCIENCE 6A October 29th, 202 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, we will eventually

### CSCE 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

### Shell 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.

### CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

CS115 INTRODUCTION TO COMPUTER SCIENCE 1 Additional Notes Module 5 Example my-length (Slide 17) 2 (define (my-length alos) [(empty? alos) 0] [else (+ 1 (my-length (rest alos)))])) (my-length empty) alos

### CS61A Midterm 2 Review (v1.1)

Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

### Notes on Higher Order Programming in Scheme. by Alexander Stepanov

by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

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

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

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

Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst

### 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.

Oct 07, 16 18:11 Page 1/10 * Lecture 02 Set Implicit Arguments. Inductive list (A: Type) : Type := nil : list A cons : A > list A > list A. Fixpoint length (A: Type) (l: list A) : nat := nil _ => O cons

### Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

Lambda Calculus CS 550 Programming Languages Jeremy Johnson 1 Lambda Calculus The semantics of a pure functional programming language can be mathematically described by a substitution process that mimics

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

Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process

### Functions and Recursion. Dr. Philip Cannata 1

Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,

### LECTURE 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

(add1 3) 4 (check-expect (add1 3) 4) (define T 7) (define (q z) (sqr z)) (cond [(> T 3) (q 4)] [else 9]) (cond [(> T 3) (q 4)] [else 9]) -->[const] ^ (cond [(> 7 3) (q 4)] [else 9]) -->[arith] ^^^^^^^

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

6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

### Lisp Basic Example Test Questions

2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2

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

Integrated Introduction to Computer Science Klein Homework 6: Higher-Order Procedures Due: 11:59 PM, Oct 16, 2018 Contents 1 Fun with map (Practice) 2 2 Unfold (Practice) 3 3 Map2 3 4 Fold 4 5 All You

### Streams and Evalutation Strategies

Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

### Functional programming with Common Lisp

Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

### 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))

CS61A Notes 02b Fake Plastic Trees Box and Pointer Diagrams QUESTIONS: Evaluate the following, and draw a box-and-pointer diagram for each. (Hint: It may be easier to draw the box-and-pointer diagram first.)

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

CS 61A Midterm #2 ver1.03 -- March 2, 1998 Exam version: A Your name login: cs61a- Discussion section number TA's name Look at the edge of your seat. Write your ROOM, seat row and number. Your row number

### Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

### An introduction to Scheme

An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

### Box-and-arrow Diagrams

Box-and-arrow Diagrams 1. Draw box-and-arrow diagrams for each of the following statements. What needs to be copied, and what can be referenced with a pointer? (define a ((squid octopus) jelly sandwich))

### The Typed Racket Guide

The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

### April 2 to April 4, 2018

MORE SCHEME COMPUTER SCIENCE MENTORS 61A April 2 to April 4, 2018 1 Scheme 1. What will Scheme output? Draw box-and-pointer diagrams to help determine this. (a) (cons (cons 1 nil) (cons 2 (cons (cons 3

### CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian

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

Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2017 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, but

### Processadors 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

### Structure and Interpretation of Computer Programs

CS 6A Spring 203 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

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

Using Symbols in Expressions (1) (define z y) z Symbol y z ==> y prints as (+ x 3) evaluate sub-expressions... PrimProc Number Number ( ) machine code to add 23 3 Number 26 apply... ==> 26 prints as 1

### 1.3. Conditional expressions To express case distinctions like

Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

### An Explicit-Continuation Metacircular Evaluator

Computer Science (1)21b (Spring Term, 2018) Structure and Interpretation of Computer Programs An Explicit-Continuation Metacircular Evaluator The vanilla metacircular evaluator gives a lot of information

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

HIERARCHICAL DATA 5 COMPUTER SCIENCE 61AS Concepts and Definitions 1. What is a Tree? How is it different from a Deep List? When would you use one over the other? A Tree is an Abstract Data Type composed

### Building a system for symbolic differentiation

Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

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

Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2012 Reading 1. (Required) Mitchell, Chapter 3. 2. (As Needed) The Lisp Tutorial from the Links web page, as needed for the programming questions.

### CSE 341 Section Handout #6 Cheat Sheet

Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

### Chapter 1. Fundamentals of Higher Order Programming

Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

### Introduction to Functional Programming

Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

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

Oct 04, 16 21:55 Page 1/10 * Lecture 02 Infer some type arguments automatically. Set Implicit Arguments. Note that the type constructor for functions (arrow " >") associates to the right: A > B > C = A

### CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

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

Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define

### CS 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

### Functions, Conditionals & Predicates

Functions, Conditionals & Predicates York University Department of Computer Science and Engineering 1 Overview Functions as lambda terms Defining functions Variables (bound vs. free, local vs. global)

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

Name: BU ID (no dashes): CS 320 Homework One Due 2/5 11:59pm Write your answers to the problems in the space indicated. Scan your solution and submit to Gradescope as a PDF file. You will receive an email

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

Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation

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

1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,

### CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

### 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

6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,