Loops in Scheme, II. (early slides assume map/filter)

Similar documents
Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Module 8: Local and functional abstraction

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

From Scheme to Java. So far, we ve translated data definitions: ; A snake is ; (make-snake sym num sym) (define-struct snake (name weight food))

How to Design Programs

CS115 - Module 10 - General Trees

Wednesday, November 5

Rewriting your function using map and foldr

From FP to OOP. Start with data: class Posn { int x; int y; Posn(int x, int y) { this.x = x; this.y = y; } }

Functions in Scheme. From Scheme to Java. Functions in Java. Functions in Java. method that is in the class // Determines whether it s < n lbs

CS115 - Module 9 - filter, map, and friends

CSU211 Exam 2 Fall 2007

CSCC24 Functional Programming Scheme Part 2

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

Local defini1ons. Func1on mul1ples- of

ormap, andmap, and filter

User-defined Functions. Conditional Expressions in Scheme

Module 5: Lists. Readings: HtDP, Sections 9, 10.

CS2500 Exam 2 Fall 2011

CS2102: Lecture on Abstract Classes and Inheritance. Kathi Fisler

CS1102: Adding Error Checking to Macros

Module 9: Trees. If you have not already, make sure you. Read How to Design Programs Sections 14, 15, CS 115 Module 9: Trees

Module 10: General trees

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

CSE 341 Section Handout #6 Cheat Sheet

Basic Scheme February 8, Compound expressions Rules of evaluation Creating procedures by capturing common patterns

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

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

CS1 Recitation. Week 2

From Templates to Folds

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

CS61A Midterm 2 Review (v1.1)

Adding Machine Run 2

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

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

Code example: sfact SICP Explicit-control evaluator. Example register machine: instructions. Goal: a tail-recursive evaluator.

Functional Programming. Pure Functional Programming

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

Type Systems. Seman&cs. CMPT 379: Compilers Instructor: Anoop Sarkar. anoopsarkar.github.io/compilers-class

CS115 - Module 4 - Compound data: structures

Intro. Scheme Basics. scm> 5 5. scm>

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

Working with recursion. From definition to template. Readings: HtDP, sections 11, 12, 13 (Intermezzo 2).

Working with recursion

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

CS 115 Lecture Notes Winter 2019

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

CS115 - Module 8 - Binary trees

CS 1101 Exam 3 A-Term 2013

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

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

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

Case Study: Undefined Variables

Lecture 5: Implementing Lists, Version 1

6.001 Notes: Section 8.1

CS1102: Macros and Recursion

Sample midterm 1 #1. Problem 1 (What will Scheme print?).

Administrivia. Simple data types

Repetition Through Recursion

Topic 5: Higher Order Functions

Topic 5: Higher Order Functions

CS 314 Principles of Programming Languages. Lecture 16

Homework 6: Higher-Order Procedures Due: 10:00 PM, Oct 17, 2017

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

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

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

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

Module 3: New types of data

CMSC 330: Organization of Programming Languages. Operational Semantics

Expression Values Operators. (string-append a b c ) a, b, c string-append. (substring abcd 0 2) abcd, 0, 2 substring

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

Higher-Order Functions

CS115 - Module 3 - Booleans, Conditionals, and Symbols

Dependencies by case or by function?

CS 440: Programming Languages and Translators, Spring 2019 Mon

Racket: Modules, Contracts, Languages

Lecture 4: Inheritence and Abstract Classes

Functional Programming - 2. Higher Order Functions

CITS3211 FUNCTIONAL PROGRAMMING. 6. Folding operators

Outline. Helper Functions and Reuse. Conditionals. Evaluation Rules for cond. Design Recipe with cond. Compound Data

CS 135 Fall 2018 Final Exam Review. CS 135 Fall 2018 Final Exam Review 1

CS3 Midterm 2 Summer 2008

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

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

6.001: Structure and Interpretation of Computer Programs

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

Functional programming with Common Lisp

Building a system for symbolic differentiation

Department of Computer Science Purdue University, West Lafayette

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

CS1102: What is a Programming Language?

Module 8: Binary trees

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

(Provisional) Lecture 08: List recursion and recursive diagrams 10:00 AM, Sep 22, 2017

Higher Order Functions in Haskell

Streams and Evalutation Strategies

Racket Pattern Matching

Transcription:

Loops in Scheme, II (early slides assume map/filter) c. Kathi Fisler, 2001

Recap: filter and map filter and map are Scheme s loops filter : (α! boolean) list[α]! list[α] extract list of elts that satisfy a predicate map:(α! β) list[α]! list[β] applies function to all elts, returning list of results

Recall sum ;; sum : list[num]! num ;; adds up the elements of a list of numbers (define (sum alon) (cond [(empty? alon) 0] (+ (first alon) (sum (rest alon)))])) Sum also loops; how to write it with filter/map? [try it]

filter/map don t work for sum Both return lists -- sum returns a number Sum requires another kind of loop We derived filter by looking at two programs with similar structure and abstracting the common parts into a helper function

sum and product ;; sum : list[num]! num ;; adds elts of a list of nums (define (sum alon) (cond [(empty? alon) 0] (+ (first alon) (sum (rest alon)))])) ;; prod : list[num]! num ;; multiplies list of nums (define (prod alon) (cond [(empty? alon) 1] (* (first alon) (prod (rest alon)))])) Where do these two programs differ?

sum and product ;; sum : list[num]! num ;; adds elts of a list of nums (define (sum alon) (cond [(empty? alon) 0] (+ (first alon) (sum (rest alon)))])) ;; prod : list[num]! num ;; multiplies list of nums (define (prod alon) (cond [(empty? alon) 1] (* (first alon) (prod (rest alon)))])) Make the blue parts parameters to a new function [try it]

The New Loop ;; newloop :? num list[num]! num Write sum and product using newloop [try it]

The New Loop ;; newloop :? num list[num]! num ;; sum : list[num]! num (define (sum alon) (newloop + 0 alon) ;; prod : list[num]! num (define (prod alon) (newloop * 1 alon)

The New Loop ;; newloop :? num list[num]! num Write length (of a list) using newloop [try it] base and alon arguments are easy but combine

The New Loop ;; newloop :? num list[num]! num What is combine s contract? [try it] ;; combine :! (we see from its use that it takes two arguments)

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : What type is (first alon)?! A number, by contract

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : num! What type is (first alon)? A number, by contract

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : num! What type is (newloop (rest alon))? A number, by contract

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : num num! What type is (newloop (rest alon))? A number, by contract

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : num num! What does combine return? A number (by contract) since newloop returns the result of combine

The New Loop ;; newloop :? num list[num]! num What is combine s contract? ;; combine : num num! num What does combine return? A number (by contract) since newloop returns the result of combine

The New Loop ;; newloop : (num num! num) num list[num]! num So, combine has contract ;; combine : num num! num OK, but how do we write combine for length?

The New Loop ;; newloop : (num num! num) num list[num]! num Combine takes the first elt of the list and the result of looping on the rest of the list. So, your combine function determines how to put these together

The New Loop ;; newloop : (num num! num) num list[num]! num ;; combine : num num! num (lambda (elt result-rest) ) (this naming convention on combine functions reminds you what the args stand for)

The New Loop ;; newloop : (num num! num) num list[num]! num ;; combine : num num! num (lambda (elt result-rest) (+ 1 result-rest)) For length, we don t care about the contents of the elt, just that it exists. Combine therefore ignores elt.

The New Loop ;; newloop : (num num! num) num list[num]! num ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst)) [stretch break]

But wait ;; newloop : (num num! num) num list[num]! num The contracts don t match! ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst))

Fixing the newloop contract ;; newloop : (num num! num) num list[α]! num If we change num to α, what else must change in the newloop contract? ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst))

Fixing the newloop contract ;; newloop : (num num! num) num list[α]! num Where is the α processed in newloop? ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst))

Fixing the newloop contract ;; newloop : (α num! num) num list[α]! num So the first argument to combine must also be α ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst))

Fixing the newloop contract ;; newloop : (α num! num) num list[α]! num This fixes the contract wrt length; now consider newloop alone ;; length : list[α]! num (define (length alst) (newloop (lambda (elt result-rest) (+ 1 result-rest)) 0 alst))

Stepping back: newloop ;; newloop : (α num! num) num list[α]! num What in the definition of newloop requires it to output a number? (newloop has no arith ops ) What if we wanted a loop that returned a boolean, or a structure, or?

Generalizing newloop ;; newloop : (α num! num) num list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β?

Generalizing newloop ;; newloop : (α num! num) num list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? Where does the output of newloop come from?

Generalizing newloop ;; newloop : (α num! num) num list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? Where are these types in the contract?

Generalizing newloop ;; newloop : (α num! β) β list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? Change these types to β

Generalizing newloop ;; newloop : (α num! β) β list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? What about that lingering num? (where is it from)?

Generalizing newloop ;; newloop : (α num! β) β list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? The num is the second argument to combine

Generalizing newloop ;; newloop : (α num! β) β list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? But this value comes from the output of newloop!

Generalizing newloop ;; newloop : (α β! β) β list[α]! β Let s change the contract to let newloop return a value of any type. What else in the contract must change to β? So this num must also become a β

At long last ;; newloop : (αβ! β) β list[α]! β Actually, newloop is built-in. It s called foldr

The foldr loop ;; foldr : (αβ! β) β list[α]! β (define (foldr combine base alst) (cond [(empty? alst) base] [(cons? alst) (combine (first alst) (foldr (rest alst)))])) ;; length : list[α]! num (define (length alst) (foldr (lambda (elt result-rest) (+ 1 result-rest)) 0 alon))

Phew! We now have three loops at our disposal: filter : (α! boolean) list[α]! list[α] extract list of elts that satisfy a predicate map:(α! β) list[α]! list[β] applies function to all elts, returning list of results foldr : (αβ! β) β list[α]! β combines elts of list according to given function

Time to practice! Recall the data defns for animal/boa/armadillo ;; A boa is a (make-boa symbol num symbol) (define-struct boa (name length food)) ;; An armadillo is a (make-dillo symbol num bool) (define-struct dillo (name length dead?)) ;; An animal is one of ;; - a boa ;; - an armadillo

Time to practice! Write the following programs with Scheme loops ;; large-animals : list[animal] num! list[animal] ;; return list of all animals longer than given num ;; eats-pets-count : list[animal]! num ;; return number of boas in list that eat pets ;; kill-all-dillos : list[animal]! list[animal] ;; return list containing all animals in the input list ;; but with all armadillos dead