Recursive List Func.ons in Racket

Similar documents
Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Programming with Pairs and Lists. Box-and-pointer diagrams for cons trees

Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Pairs and Lists in Racket. Box-and-pointer diagrams for cons trees

Overview. Iteration via Tail Recursion in Racket. Factorial Revisited. An itera*ve approach to factorial. What is itera*on?

Func+on applica+ons (calls, invoca+ons)

CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College

Overview. Factorial Revisited. Iteration via Tail Recursion in Racket. An itera*ve approach to factorial. What is itera*on?

Overview. Iteration via Tail Recursion in Racket SOLUTIONS. Factorial Revisited. An itera*ve approach to factorial

PostFix. PostFix command semanccs (except exec) PostFix Syntax. A PostFix Interpreter in Racket. CS251 Programming Languages Fall 2017, Lyn Turbak

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

Local defini1ons. Func1on mul1ples- of

LISP: LISt Processing

CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College

PostFix. PostFix command semanccs (except exec) PostFix Syntax. A PostFix Interpreter in Racket. CS251 Programming Languages Spring 2018, Lyn Turbak

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

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

How to Design Programs

Problem Set 2 Solutions

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

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

List Processing in Ocaml

A brief tour of history

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

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

Lists. CS 5010 Program Design Paradigms Bootcamp Lesson 4.1

Discussion 4. Data Abstraction and Sequences

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

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

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

Introduc)on To Standard ML

Module 9: Binary trees

Module 10: General trees

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

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

Modules and Representa/on Invariants

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm Sample Solutions CSC324H1 Duration: 50 minutes Instructor(s): David Liu.

CS115 - Module 10 - General Trees

User-defined Functions. Conditional Expressions in Scheme

GADTs. Wouter Swierstra and Alejandro Serrano. Advanced functional programming - Lecture 7. [Faculty of Science Information and Computing Sciences]

Func%onal Programming in Scheme and Lisp

Trees. Binary arithmetic expressions. Visualizing binary arithmetic expressions. ((2 6) + (5 2))/(5 3) can be defined in terms of two smaller

Fruitful Recursion (recursion that returns a value)

GADTs. Alejandro Serrano. AFP Summer School. [Faculty of Science Information and Computing Sciences]

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

CS 314 Principles of Programming Languages. Lecture 16

Func%onal Programming in Scheme and Lisp

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS

Lecture 6: Sequential Sorting

Valex: Mul*ple Value Types, Condi*onals, Dynamic Type Checking and Desugaring

Topic 5: Examples and higher-order functions

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

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

Working with recursion

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

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

Valex: Mul*ple Value Types, Condi*onals, Dynamic Type Checking and Desugaring SOLUTIONS

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

From Templates to Folds

Func%ons (Math) Func%on Defini%ons. Func%ons (Computer Sciences) Func%on = mappings or transforma%ons Math examples:

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

Sum-of-Product (SOP) Datatypes in SML

Dynamic Data Types - Recursive Records

Fall 2017 December 4, Scheme. Instructions

Laboratory: Recursion Basics

CPSC 311, 2010W1 Midterm Exam #2

CS2500 Exam 2 Fall 2011

Accurate Step Counting

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

April 2 to April 4, 2018

CS 314 Principles of Programming Languages

Repetition Through Recursion

Functional Programming - 2. Higher Order Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

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

Trees. Readings: HtDP, sections 14, 15, 16.

CS251 Programming Languages Handout # 29 Prof. Lyn Turbak March 7, 2007 Wellesley College

GADTs. Wouter Swierstra. Advanced functional programming - Lecture 7. Faculty of Science Information and Computing Sciences

Introduction to Recursion

Bindex: Naming, Free Variables, and Environments

List Processing in SML

Bindex: Naming, Free Variables, and Environments SOLUTIONS

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

Multiplying and Dividing by Powers of 10

Problem Set 5 Due: Friday, November 2

List Processing in SML

CSCE 314 Programming Languages

Functional Programming. Pure Functional Programming

COMP Lecture Notes Iterative and Recursive Procedures for Strings

Shell CSCE 314 TAMU. Higher Order Functions

Module 8: Binary trees

CS 320: Concepts of Programming Languages

CSc 520. Gofer III. Accumulative Recursion. Accumulative Recursion... Stack Recursion. Principles of Programming Languages. Christian Collberg

FOFL and FOBS: First-Order Functions

Problem Set 1 Due: 11:59pm Wednesday, February 7

CS 314 Principles of Programming Languages

Structure and Interpretation of Computer Programs

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

Encodings. Using the minimal λ-calculus language we get. functions. local binding. booleans. numbers... and recursive functions?

A Brief Introduction to Scheme (II)

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

Transcription:

Recursive List Func.ons in Racket Because Racket lists are defined recursively, it s natural to process them recursively. Typically (but not always) a recursive func.on recf on a list argument L has two cases: base case: what does recf return when L is empty? (Use? to test for an empty list.) CS251 Programming Languages Fall 2018, Lyn Turbak recursive case: if L is the nonempty list (cons Vfirst Vrest) how are Vfirst and (recf Vrest)d to give the result for(recf L)? Department of Computer Science Wellesley College Note that we always ``blindly apply recf to Vrest! 2 Recursive List Func.ons: Divide/Conquer/Glue (DCG) strategy for the general case [in words] Step 1 (concrete example): pick a concrete input list, typically 3 or 4 elements long. What should the func.on return on this input? E.g. A sum func.on that returns the sum of all the numbers in a list: (sum '(5 7 2 4)) * 18 Step 2 (divide): without even thinking, always apply the func.on to the rest of the list. What does it return? (sum '(7 2 4)) * 13 Step 3 (glue): How to the first element of the list (in this case, 5) with the result from processing the rest (in this case, 13) to give the result for processing the whole list (in this case, 18)? ( 5 (sum '(7 2 4)) * 18 Step 4 (generalize): Express the general case in terms of an arbitrary input: (define (sum nums) ( (first nums) (sum (rest nums)) ) 3 Recursive List Func.ons: Divide/Conquer/Glue (DCG) strategy for the general case [in diagram] (sum '( 5 7 2 4 )) * 18 (sum '(7 2 4)) * 13 Divide: what should func.on return for rest of list? (wishful thinking!) Glue: how to the first element of the list with the result of recursively processing rest of the list to get the desired result for the whole list? Solu.on for concrete example: ( 5 (sum '(7 2 4)) Generaliza.on of concrete solu.on: ( (first nums) (sum (rest nums)) 4

Recursive List Func.ons: base case via singleton case Deciding what a recursive list func.on should return for the empty list is not always obvious and can be tricky. E.g. what should (sum '()) return? If the answer isn t obvious, consider the ``penul.mate case in the recursion, which involves a list of one element: (sum '( 4 )) * 4 Divide: what value V should func.on return for empty list? (sum '()) * V Pu_ng it all together: base & general cases (sum nums) returns the sum of the numbers in the list nums (define (sum ns) (if (? ns) 0 ( (first ns) (sum (rest ns))))) In this case, V should be 0, which is the iden.ty element for addi.on. But in general it depends on the details of the par.cular r determined from the general case. So solve the general case before the base case! 5 6 Understanding sum: Approach #1 Understanding sum: Approach #2 (sum '(7 2 4)) In (sum (list 7 2 4)), the list argument to sum is 7 2 4 0 (cons 7 (cons 2 (cons 4 )))) Replace cons by and by 0 and simplify: ( 7 ( 2 ( 4 0)))) 4 ( 7 ( 2 4))) 6 ( 7 6) 13 13 We ll call this the recursive accumulaaon pafern 5-7 Pairs and Lists 8

Generalizing sum: Approach #1 (recf (list 7 2 4)) Generalizing sum: Approach #2 In (recf (list 7 2 4)), the list argument to recf is 7 2 4 val (cons 7 (cons 2 (cons 4 )))) Replace cons by and by val and simplify: ( 7 ( 2 ( 4 val )))) Pairs and Lists 9 10 Generalizing the sum defini.on (define (recf ns) (if (? ns) val ( (first ns) (recf (rest ns))))) Your turn Define the following recursive list func.ons and test them in Racket: (product ns) returns the product of the numbers in ns (min-list ns) returns the minimum of the numbers in ns Hint: use min and inf.0 (posi.ve infinity) (max-list ns) returns the minimum of the numbers in ns Hint: use max and -inf.0 (nega.ve infinity) (all-true? bs) returns #t if all the elements in bs are truthy; otherwise returns #f. Hint: use and (some-true? bs) returns a truthy value if at least one element in bs is truthy; otherwise returns #f. Hint: use or 11 (my-length xs) returns the length of the list xs 12

Recursive Accumula.on Pafern Summary Define these using Divide/Conquer/Glue val sum 0 product * 1 min-list min inf.0 max-list max -inf.0 all-true? and #t some-true? or #f my-length (λ (fst subres) ( 1 subres)) 0 > (snoc 11 '(7 2 4)) '(7 2 4 11) > (my-append '(7 2 4) '(5 8)) '(7 2 4 5 8) > (append-all '((7 2 4) (9) () (5 8))) '(7 2 4 9 5 8) > (my-reverse '(5 7 2 4)) '(4 2 7 5) 13 14 Mapping Example: map-double (map-double ns) returns a new list the same length as ns in which each element is the double of the corresponding element in ns. > (map-double (list 7 2 4)) '(14 4 8) (define (map-double ns) (if (? ns) ; Flesh out base case Understanding map-double (map-double '(7 2 4)) 7 * 2 2 * 2 4 * 2 14 4 8 ; Flesh out general case We ll call this the mapping pafern )) 15 16

Generalizing map-double (mapf (list V1 V2 Vn)) Expressing mapf as an accumula.on V1 V2 Vn F (F v1) F F (F v2) (F vn) (define (mapf xs) (if (? xs) ((λ (fst subres) ) ; Flesh this out (first xs) (mapf (rest xs))))) (define (mapf xs) (if (? xs) (cons (F (first xs)) (mapf (rest xs))))) 17 18 Some Recursive Lisluns Need Extra Args (define (map-scale factor ns) (if (? ns) (cons (* factor (first ns)) (map-scale factor (rest ns))))) Filtering Example: filter-positive (filter-positive ns) returns a new list that contains only the posi.ve elements in the list of numbers ns, in the same rela.ve order as in ns. > (filter-positive (list 7-2 -4 8 5)) '(7 8 5) (define (filter-positive ns) (if (? ns) ; Flesh out base case ; Flesh out recursive case )) 19 20

Understanding filter-positive (filter-positive (list 7-2 -4 8 5)) 7-2 -4 8 5 Generalizing filter-positive (filterp (list V1 V2 Vn)) V1 V2 Vn P P P #t #f #f #t #t #t #f #t V1 Vn 7 8 5 We ll call this the filtering pafern 21 (define (filterp xs) (if (? xs) (if (P (first xs)) (cons (first xs) (filterp (rest xs))) (filterp (rest xs))))) 22 Expressing filterp as an accumula.on (define (filterp xs) (if (? xs) ((lambda (fst subres) ) ; Flesh this out (first xs) (filterp (rest xs))))) 23