Local defini1ons. Func1on mul1ples- of

Similar documents
Module 8: Local and functional abstraction

Local definitions and lexical scope

Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

CS115 - Module 9 - filter, map, and friends

Module 10: Imperative Programming, Modularization, and The Future

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

Functional abstraction

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

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

Working with recursion

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

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

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

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

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

CS2500 Exam 2 Fall 2011

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

Module 3: New types of data

ormap, andmap, and filter

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

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

Thinking Induc,vely. COS 326 David Walker Princeton University

Module 9: Binary trees

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

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

Style and Submission Guide

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

Overview. A mathema5cal proof technique Proves statements about natural numbers 0,1,2,... (or more generally, induc+vely defined objects) Merge Sort

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

Func%ons. CS449 Fall 2017

CS115 - Module 10 - General Trees

Functional Programming. Pure Functional Programming

Module 10: General trees

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

CS115 - Module 4 - Compound data: structures

How to Design Programs Languages

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

CS115 - Module 3 - Booleans, Conditionals, and Symbols

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

CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local. CS 135 Winter 2018 Tutorial 8: Mutual recursion, nested lists, and local 1

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

Scheme Quick Reference

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

The Design Recipe Fall 2017

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

Scheme Quick Reference

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

CS 115 Lecture Notes Winter 2019

Functional Programming - 2. Higher Order Functions

Array Basics: Outline

CSE 341 Section Handout #6 Cheat Sheet

CS115 INTRODUCTION TO COMPUTER SCIENCE 1. Additional Notes Module 5

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

CS 1101 Exam 3 A-Term 2013

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

How to Design Programs

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

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

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

Recursive List Func.ons in Racket

Racket Style Guide Fall 2017

Module 4: Compound data: structures

CS 320: Concepts of Programming Languages

CMSC 131A, Midterm 1 (Practice) SOLUTION. Fall 2017

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

CSC 533: Programming Languages. Spring 2015

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Writing a Fraction Class

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

The Design Recipe Fall 2018

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

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

List Processing Patterns and List Comprehension

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

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

Tuples. CMSC 330: Organization of Programming Languages. Examples With Tuples. Another Example

CSE341 Spring 2016, Final Examination June 6, 2016

Chapter 2, Part III Arithmetic Operators and Decision Making

F28PL1 Programming Languages. Lecture 14: Standard ML 4

Finally, all fields are public by default, so you can easily write simple functions, such as this one, without writing getters:

COMP-520 GoLite Tutorial

Programming Languages and Techniques (CIS120)

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

List Processing Patterns and List Comprehension

Typed Racket: Racket with Static Types

University of Massachusetts Lowell

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

The Typed Racket Guide

Scheme as implemented by Racket

Module 8: Binary trees

NOTE: Answer ANY FOUR of the following 6 sections:

6.001 Notes: Section 6.1

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

Discussion 4. Data Abstraction and Sequences

ALGORITHM 2-1 Solution for Exercise 4

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

Functional Programming. Big Picture. Design of Programming Languages

Encapsula)on CMSC 202

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

Transcription:

Local defini1ons The func1ons and special forms we ve seen so far can be arbitrarily nested except define and check- expect. So far, defini.ons have to be made at the top level, outside any expression. The Intermediate language provides the special form local, which contains a series of local defini.ons plus an expression using them, of the form What use is this? (def 1... def n ) exp) local groups related defini1ons for use in expression. Each defini1on can be either a define or a define- struct. CS 115 Fall 2015 10: Local and func1onal abstrac1on 2 Func1on mul1ples- of Suppose we want to use abstract list func1ons to solve: Write a func1on mul1ples- of that consumes a posi1ve integer, n, and a list of integers, ilist, and produces a new list containing ONLY those values in ilist which are mul1ples of n. Our auempt: (define (is- mult? m) (zero? (remainder m n))) (define (mul1ples- of n ilist) (filter is- mult? ilist)) fails. Why? (define ilist (list 1 2 3 4 5 6) ;; Example (mul1ples- of 2 ilist) => (list 2 4) (mul1ples- of 3 ilist) => (list 3 6) CS 115 Fall 2015 10: Local and func1onal abstrac1on 3 1

Local defini1ons (cont.) (define (mul1ples- of n ilist) ( ;; (is- mult? m) produces ;; true if m is a mul1ple of n, ;; and false otherwise. ;; is- mult?: Int Bool (define (is- mult? m) (zero? (remainder m n)))) (filter is- mult? ilist))) (define (is- mult? m) (zero? (remainder m n))) (define (mul1ples- of n ilist) (filter is- mult? ilist)) n only exists within the body of mul1ples- of The combine func1on is- mult? needs the value of n but to be used by filter, it can only accept one parameter - an element of the list. CS 115 Fall 2015 10: Local and func1onal abstrac1on 4 Func1on mul1ples- of (cont.) Note: Provide purpose, contract, and requirements for local helper func1ons. REMEMBER (define (mul1ples- of n ilist) [ ;; (is- mult? m) produces ;; true if m is a mul1ple of n, ;; and false otherwise. ;; is- mult?: Int Bool (define (is- mult? m) (zero? (remainder m n)))] (filter is- mult? ilist))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 5 2

Another Example: func1on swap- parts Recall the func1on swap- parts from Module 2. The func1on used three helper func1ons. (define (mid num) (quo1ent num 2)) (define (front- part mystring) (substring mystring 0 (mid (string- length mystring)))) (define (back- part mystring) (substring mystring (mid (string- length mystring)) (string- length mystring))) Hi, Hi,All All AllHi, CS 115 Fall 2015 10: Local and func1onal abstrac1on 6 Func1on swap- parts (cont.) (define (swap- parts mystring) (string- append (back- part mystring) (front- part mystring))) The helper func1on mid is a helper func1on of the helper func1ons front- part and back- part. Our solu1on was perfectly acceptable. However, repeated applica1ons, such as (mid (string- length mystring)), make it a bit hard to read. CS 115 Fall 2015 10: Local and func1onal abstrac1on 7 3

Func1on swap- parts (cont.) (define (swap- parts mystring) ((define mid (quo1ent (string- length mystring) 2)) (define front (substring mystring 0 mid)) (define back (substring mystring mid (string- length mystring)))) (string- append back front))) (def 1 def 2 def 3 ) exp) The special form local allows us to define a constant or a func.on within another func1on. It would be nice to replace repeated applica1ons by a constant. Note: mid, front, and back are constants, not func1ons, so they have no contracts. CS 115 Fall 2015 10: Local and func1onal abstrac1on 8 Local double parentheses Like cond, local results in double parentheses. Op1onal: use square brackets to improve readability. (define (swap- parts mystring) [(define mid (quo1ent (string- length mystring) 2)) (define front (substring mystring 0 mid)) (define back (substring mystring mid (string- length mystring)))] (string- append back front))) Defini1on Part CS 115 Fall 2015 10: Local and func1onal abstrac1on 9 4

Re- using names with local A define within a local expression may rebind a name that has already been bound to another value or expression. (define (my- fun n m) [(define n 12) (define - fun n) ( n 10))] (+ m - fun n)))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 10 Prac1cal Exercise Using abstract list func1ons and local, write the func1on scale-points which consumes a list of posns and a number k, and produces a list of posns where each co- ordinate value (i.e., both x and y) are scaled (i.e., mul.plied by) the value k. Any helper func1ons must be declared using local. You must not use recursion to solve this problem. (define (scale- points alop k) [(define (scale- posn aposn) (make- posn (* k (posn- x aposn)) (* k (posn- y aposn))))] (map scale- posn alop))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 11 5

Nested local expression It isn t always possible to define local at the beginning of the func1on defini1on, because the defini1on might make assump1ons that are only true in part of the code. A typical example is that of using a list func1on, like first or rest, which must consume a nonempty list. When there is one local defini1on that can be used throughout and one not, we end up with nested local expressions. CS 115 Fall 2015 10: Local and func1onal abstrac1on 12 Nested local expression (define (avg- nums lst) [(define only- nums (filter number? lst))] (cond [(empty? only- nums) no- nums] [else [(define num- sum (foldr + 0 only- nums)) (define num- nums (length only- nums))] (/ num- sum num- nums)) ] ) )) CS 115 Fall 2015 10: Local and func1onal abstrac1on 13 6

Using local for common sub- expressions A sub- expression used twice within a func1on body always yields the same value. Using local to give the reused sub- expression a name improves the readability of the code. In the following example, the func1on eat- apples removes all occurrences of the symbol apple from a list of symbols. The sub- expression (eat- apples (rest alist)) occurs twice in the code. CS 115 Fall 2015 10: Local and func1onal abstrac1on 14 The func1on eat- apples (define (eat- apples alist) (cond [(empty? alist) empty [(cons? alist) (cond [(not (symbol=? (first alist) apple)) (cons (first alist) (eat- apples (rest alist)))] [else (eat- apples (rest alist))])])) (define (eat- apples alist) (cond Using [(empty? alist) empty] local [(cons? alist) [(define ate- rest (eat- apples (rest alist)))] (cond [(not (symbol=? (first alist) apple)) (cons (first alist) ate- rest)] [else ate- rest]))])) CS 115 Fall 2015 10: Local and func1onal abstrac1on 15 7

Using local can improve efficiency Module 2 Module 10 (define (mid num) (quo1ent num 2)) (define (front- part mystring) (substring mystring 0 (mid (string- length mystring)))) (define (back- part mystring) (substring mystring (mid (string- length mystring)) (string- length mystring))) (define (swap- parts mystring) (string- append (back- part mystring) (front- part mystring))) (define (swap- parts mystring) ((define mid (quo1ent (string- length mystring) 2)) (define front (substring mystring 0 mid)) (define back (substring mystring mid (string- length mystring)))) (string- append back front))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 16 Using local for smaller tasks Some1mes we choose to use local in order to name sub- expressions in a way to make the code more readable, even if they are not reused. This may make the code longer, but may improve clarity. Recall our func1on to compute the distance between two points. (define (distance posn1 posn2) (sqrt (+ (sqr ( (posn- x posn1) (posn- x posn2))) (sqr ( (posn- y posn1) (posn- y posn2)))))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 17 8

Using local for smaller tasks (cont.) (define (distance posn1 posn2) (sqrt (+ (sqr ( (posn- x posn1) (posn- x posn2))) (sqr ( (posn- y posn1) (posn- y posn2)))))) (define (distance posn1 posn2) [(define delta- x ( (posn- x posn1) (posn- x posn2))) (define delta- y ( (posn- y posn1) (posn- y posn2))) (define sqrsum (+ (sqr delta- x) (sqr delta- y)))] (sqrt sqrsum))) CS 115 Fall 2015 10: Local and func1onal abstrac1on 18 Using local for encapsula1on Encapsula1on is the process of grouping things together in a capsule. We have already seen data encapsula1on in the use of structures. Encapsula1on can also be used to hide informa1on. Here the local bindings are not visible outside the local expression. CS 115 Fall 2015 10: Local and func1onal abstrac1on 19 9

Full design recipe Note that a full design recipe is not needed for local helper func1ons on assignment submissions. You should s1ll develop examples and tests for helper func1ons, and test them outside local expressions if possible. Once you have confidence that they work, you can move them into a local expression, and delete the examples and tests. A contract and purpose are s1ll required (omiued in these slides for space reasons). CS 115 Fall 2015 10: Local and func1onal abstrac1on 20 Goals of this module You should understand the idea of encapsula.on of local helper func1ons. You should be familiar with map, filter, and foldr, understand how they abstract common recursive pauerns, and be able to use them to write code. You should understand the idea of func1ons as first- class values, and how they can be supplied as arguments. CS 115 Fall 2015 10: Local and func1onal abstrac1on 21 10

Goals of this module (cont.) You should be able to use local to avoid repe11on of common sub- expressions, to improve readability of expressions, and to improve efficiency of code. You should be able to match the use of any constant or func1on name in a program to the binding to which it refers. CS 115 Fall 2015 10: Local and func1onal abstrac1on 22 11