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

Similar documents
Administrivia. Simple data types

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

6.001 Notes: Section 5.1

Principles of Programming Languages

6.001 Notes: Section 6.1

CS450 - Structure of Higher Level Languages

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

6.001 Notes: Section 8.1

Higher-Order Procedures

CS 314 Principles of Programming Languages

A Brief Introduction to Scheme (II)

regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13

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

Functional Programming. Pure Functional Programming

6.001: Structure and Interpretation of Computer Programs. Themes to be integrated. Our target the art of M. C. Escher

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Introduction to Scheme

Today's Lecture. Programming as the process of creating a new task-specific language. data abstractions procedure abstractions higher-order procedures

Introduction to Functional Programming

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

2.2 Hierarchical Data and the Closure Property

Higher order procedures procedures as types

Building a system for symbolic differentiation

User-defined Functions. Conditional Expressions in Scheme

Building a system for symbolic differentiation

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

6.001: Structure and Interpretation of Computer Programs

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

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

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

An Explicit-Continuation Metacircular Evaluator

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


Streams and Evalutation Strategies

CS 314 Principles of Programming Languages. Lecture 16

Scheme Quick Reference

Scheme Quick Reference

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

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

Lecture #24: Programming Languages and Programs

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

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

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams

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

6.001 Notes: Section 31.1

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

Functional Programming - 2. Higher Order Functions

6.001 Notes: Section 15.1

Discussion 4. Data Abstraction and Sequences

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

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

CS61A, Fall/1999 Midterm #1 Professor Brian Harvey

A Small Interpreted Language

Sample Final Exam Questions

6.001 Notes: Section 17.5

Documentation for LISP in BASIC

CSc 520 Principles of Programming Languages

6.001, Spring Semester, 1998, Final Exam Solutions Your Name: 2 Part c: The procedure eval-until: (define (eval-until exp env) (let ((return (eval-seq

An Introduction to Scheme

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

Scheme as implemented by Racket

Typed Scheme: Scheme with Static Types

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

Repetition Through Recursion

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

CS61A Midterm 2 Review (v1.1)

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

This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

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

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

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

University of Massachusetts Lowell

CS3: Introduction to Symbolic Programming. Lecture 14: Lists.

SCHEME AND CALCULATOR 5b

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

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

CS 314 Principles of Programming Languages

Programming Languages: Application and Interpretation

Project 2: Scheme Interpreter

LECTURE 16. Functional Programming

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

Discussion 12 The MCE (solutions)

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

YOUR NAME PLEASE: *** SOLUTIONS ***

CSE413 Midterm. Question Max Points Total 100

An introduction to Scheme

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream?

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

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

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Problem 1: Binary Trees: Flatten

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

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

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

Functional abstraction

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

Problem Set 4: Streams and Lazy Evaluation

Chapter 1. Fundamentals of Higher Order Programming

C311 Lab #3 Representation Independence: Representation Independent Interpreters

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

Transcription:

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 in body of procedure Give procedure a name Hide implementation details from user, who just invokes name to apply procedure Input: type procedure Details of contract for converting input to output Output: type Procedural abstraction example: To find an approximation of square root of x: Make a guess G Improve the guess by averaging G and x/g Keep improving the guess until it is good enough (define try (lambda (guess x) (if (good-enuf? guess x) guess (try ( guess x) x)))) (define (lambda (guess x) (average guess (/ x guess)))) (define average (lambda (a b) (/ (+ a b) ))) (define good-enuf? (lambda (guess x) (< (abs (- (square guess) x)).))) (define (lambda (x) (try x))) The universe of procedures for average try Good-enuf? The universe of procedures for - Block Structure average try (define ( x) (define (good-enuf? guess) (< (abs (- (square guess) x)).)) (define ( guess) (average guess (/ x guess))) (define (-iter guess) (if (good-enuf? guess) guess (-iter ( guess)))) ( iter.)) Good-enuf? x: number good enuf? good enuf? x : number 6

Clean version of easy to add cbrt (define ( x) (fixed-point (average-damp (lambda (y) (/ x y))) )) Compare this to Heron s algorithm from before same process, but ideas intertwined with code Summary of part Procedural abstractions Isolate details of process from its use Designer has choice of which ideas to isolate, in order to support general patterns of computation Good planning in how to collect procedures within higher order structures can make it easier to add new computations (define (cbrt x) (fixed-point (average-damp (lambda (y) (/ x (square y)))) )) 7 8 Language Elements Primitives prim. data: numbers, strings, booleans primitive procedures Means of Combination procedure application compound data (today) Means of Abstraction naming compound procedures block structure higher order procedures (more today) conventional interfaces lists (today) data abstraction (next lecture) Compound data Need a way of gluing data elements together into a unit that can be treated as a simple data element Need ways of getting the pieces back out Need a contract between the glue and the unglue Ideally want the result of this gluing to have the property of closure: the result obtained by creating a compound data structure can itself be treated as a primitive object and thus be input to the creation of another compound object 9 Pairs (cons cells) Compound Data (cons <x-exp> <y-exp>) ==> <P> ;type: x, x Pair Where <x-exp> evaluates to a value <x-val>, and <y-exp> evaluates to a value <y-val> Treat a PAIR as a single unit: Can pass a pair as argument Can return a pair as a value Returns a pair <P> whose car-partis <x-val> and whose cdr-partis <y-val> (car <P>) ==> <x-val> ;type: Pair type of car part Returns the car-part of the pair <P> (define x y) (cons x y)) (define (point-x point) (car point)) (define (point-y point) (cdr point)) (, ) point (cdr <P>) ==> <y-val> ;type: Pair type of cdr part Returns the cdr-part of the pair <P> (define (make-seg pt pt) (cons pt pt)) (define (start-point seg) (car seg))

Pair Abstraction Constructor ; cons: A,B -> A X B ; cons: A,B -> Pair<A,B> (cons <x> <y>) ==> <P> Accessors (or Selectors) ; car: Pair<A,B> -> A (car <P>) ==> <x> ; cdr: Pair<A,B> -> B (cdr <P>) ==> <y> Pair abstraction Note how there exists a contract between the constructor and the selectors: (car (cons <a> <b> )) <a> (cdr (cons <a> <b> )) <b> Note how pairs have the property of closure we can use the result of a pair as an element of a new pair: (cons (cons ) ) Predicate ; pair? anytype -> boolean (pair? <z>) ==> #t if <z> evaluates to a pair, else #f Conventional interfaces -- lists A list is a data object that can hold an arbitrary number of ordered items. More formally, a list is a sequence of pairs with the following properties: Car-part of a pair in sequence holds an item Cdr-part of a pair in sequence holds a pointer to rest of list Empty -list signals no more pairs, or end of list Note that lists are closed under operations of cons and cdr. Conventional Interfaces - Lists (cons <el> <el>) <el> (list <el> <el>... <eln>) <el> <el> <el> <eln> Predicate ; null? anytype -> boolean (null? <z>) ==> #t if <z> evaluates to empty list 6 to be really careful For today we are going to create different constructors and selectors for a list (define first car) (define rest cdr) (define adjoin cons) Note how these abstractions inherit closure from the underlying abstractions! Common Pattern #: cons ing up a list (define (enumerate-interval from to) (if (> from to) (adjoin from (enumerate-interval (+ from) to)))) (e-i ) (if (> ) (adjoin (e i (+ ) ))) (if #f (adjoin (e-i ))) (adjoin (e i )) (adjoin (adjoin (e-i ))) (adjoin (adjoin (adjoin (e i )))) (adjoin (adjoin (adjoin ))) (adjoin (adjoin )) (adjoin ) ==> ( ) 7 8

Common Pattern #: cdr ing down a list Cdr ing and Cons ing Examples (define (list-ref lst n) (if (= n ) (first lst) (list-ref (rest lst) (- n )))) (define (copy lst) ; base case (adjoin (first lst) ; recursion (copy (rest lst))))) joe (list-ref joe ) (append (list ) (list )) ==> ( ) Strategy: copy list onto front of list. (+ (length (rest lst))))) 9 (define (append list list) (cond ((null? list) list) ; base (else (adjoin (first list) ; recursion (append (rest list) list))))) Common Pattern #: Transforming a List Common Pattern #: Filtering a List (define (square-list lst) (adjoin (square (first lst)) (square-list (rest lst))))) (define (double-list lst) (adjoin (* (first lst)) (double-list (rest lst))))) (define (filter pred lst) (cond ((null? lst) ) ((pred (first lst)) (adjoin (first lst) (filter pred (rest lst)))) (else (filter pred (rest lst))))) (define (map proc lst) (adjoin (proc (first lst)) (map proc (rest lst))))) (define (square-list lst) (map square lst)) (define (double-list lst) (map (lambda (x) (* x)) lst)) Common Pattern #: Accumulating Results Your Turn (define (add-up lst) (+ (first lst) (add-up (rest lst))))) (+ (length (rest lst))))) (define (mult-all lst) (* (first lst) (mult-all (rest lst))))) (define (accumulate op init lst) init (op (first lst) (accumulate op init (rest lst))))) (define (add-up lst) (accumulate + lst)) (define (accumulate op init lst) init (op (first lst) (accumulate op init (rest lst))))) Rewrite length as an accumulation (accumulate (lambda (item) ) lst))

(define make-point cons) (define point-x car) (define point-y cdr) To find the center of figure (define (centroid pts) (let ((total (length pts))) (/ (accumulate + (map point-x pts)) total) (/ (accumulate + (map point-y pts)) total)))) To shift a figure (define (shift pt offset) (- (point-x pt) (point-x offset)) (- (point-y pt) (point-y offset)))) (define (shift-figure pts offset) (map (lambda (pt) (shift pt offset)) pts)) 6 To rotate about the center (define (rotate pt) (- (point-y pt)) (point-x pt))) (define (rotate-figure pts) (let ((center (centroid pts))) (shift-figure (map rotate (shift-figure pts center)) (- (point-x center)) (- (point-y center)))))) To shift and clip (define (shift&clip pts offset) (filter (lambda (pt) (>= (point-x pt) )) (map (lambda (pt) (shift pt offset)) pts))) 7 8 Summary of part Data structures are built on contract of constructors and accessors Data structures have associated procedures for manipulation typically the recursive structure of the procedure mimics the recursive structure of the data object Building data structures Think about good organization for data Think about how procedures to manipulate structure will mimic organization of data Build and hide details of abstraction from use of abstraction, by relying on contract 9