Berkeley Scheme s OOP

Similar documents
CS61A Midterm 2 Review (v1.1)

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

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Functional Programming. Pure Functional Programming

Streams and Evalutation Strategies

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

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

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

University of Massachusetts Lowell

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

Scheme Quick Reference

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


CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CS 314 Principles of Programming Languages. Lecture 16

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

Introduction to Scheme

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

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

9 Objects and Classes


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

CS450 - Structure of Higher Level Languages

Scheme Quick Reference

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

Functional Programming. Pure Functional Languages

Evaluating Scheme Expressions

CS 314 Principles of Programming Languages

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

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

A Brief Introduction to Scheme (II)

CS 314 Principles of Programming Languages

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

User-defined Functions. Conditional Expressions in Scheme

An Introduction to Scheme

Lexical vs. Dynamic Scope

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

Review Analyzing Evaluator. CS61A Lecture 25. What gets returned by mc-eval? (not analyzing eval) REVIEW What is a procedure?

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

Write a procedure powerset which takes as its only argument a set S and returns the powerset of S.

Structure and Interpretation of Computer Programs

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

4.2 Variations on a Scheme -- Lazy Evaluation

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

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

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

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

Class 6: Efficiency in Scheme

Detection of methods (or missing methods): Cleaning up some details of our implementation. Better Method Convention (1) --self

6.001 Notes: Section 8.1

Structure and Interpretation of Computer Programs

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

Programming Languages: Application and Interpretation

CSE341 Autumn 2017, Final Examination December 12, 2017

Functional Programming. Pure Functional Languages

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

C311 Lab #3 Representation Independence: Representation Independent Interpreters

Documentation for LISP in BASIC

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

CS 360 Programming Languages Day 14 Closure Idioms

Func%onal Programming in Scheme and Lisp

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

Func%onal Programming in Scheme and Lisp

Software Design and Analysis for Engineers

Structure and Interpretation of Computer Programs

CSCC24 Functional Programming Scheme Part 2

Functional Programming

CSc 520 Principles of Programming Languages

CS 61A Discussion 8: Scheme. March 23, 2017

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

FP Foundations, Scheme

6.001, Fall Semester, 1998 Lecture Notes, October 27 { Object Oriented Programming 2 An environment diagram illustrating +define foo +cons 1 2,, +set-

Not really what happens in the computer. The Environment Model. (set-car! l 'z) (car l) z

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

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

Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

CS 360 Programming Languages Interpreters

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

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

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

UNIVERSITY of CALIFORNIA at Berkeley Department of Electrical Engineering and Computer Sciences Computer Sciences Division

Polymorphism Part 1 1

Structure and Interpretation of Computer Programs

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part,

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Building a system for symbolic differentiation

Discussion 4. Data Abstraction and Sequences

Structure and Interpretation of Computer Programs

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

Introduction to Functional Programming

CSE341 Spring 2016, Final Examination June 6, 2016

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CS 61B, Spring 1999 MT3 Professor M. Clancy

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

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

Discussion 12 The MCE (solutions)

(scheme-1) has lambda but NOT define

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

Transcription:

Page < 1 > Berkeley Scheme s OOP Introduction to Mutation If we want to directly change the value of a variable, we need a new special form, set! (pronounced set BANG! ). (set! <variable> <new-value>) (set-car! <pair> <new-value>) (set-cdr! <pair> <new-value>) To make the discussion more complete, notice that you can t use set! to change the elements inside a pair, but there are separate procedures (not special forms), set-car! and set-cdr!, to do that for you (pairs are a different data structure). These all return some unspecified value, but they change the current state 1 of the given variable or pair. Evaluating Sequences of Expressions Sometimes we have a list of expressions that need to be evaluted in a special order. Some expressions, like cond, lambda, or procedure define, automatically allow you to put multiple expressions in order (such as after the predicates in a cond and in the body of a procedure). Others, like if, are incapable of allowing multiple expressions to be listed in sequence. For these cases, you must use a Scheme special form, begin: > (begin (display I will square 5. ) (square 25) (square 5)) I will square 5. 25 Notice that the result of evaluating the begin special form is the value returned from evaluating the last expression in the list of expressions. 1 State has to do with the way a value looks. If you can mutate a value, then its form changes and we say its state changes.

Page < 2 > Interactive Abstraction of Berkeley Scheme s OOP The abstraction barrier is created in OOP by the user interfacing with the objects through a type of message passing. The programmer actually asks the object to do something and may provide needed arguments as well. One example taken from the reader is: (ask Matt-Account 'balance) the object being asked to do what You can even use actual parameters to elaborate on what your are asking. The true form of ask looks like this: (ask <object> <message> <param 1 >... <param n >) where you can have zero or more actual parameters. Message must be a symbol, so it will always be quoted. Classes & Methods Now we d like to find out how to define objects and classes (the object oriented design is an example of how expandable Scheme is since it can be written using normal Scheme expressions). To define a class you have the following form: (define-class (<class-name> <obj-param 1 >... <obj-param n >) <class-components>) The class is bound to the given symbol, class-name. The optional parameters are the instantiation variables, those variables that need specified values at the creation of an object. The body of the class, class-components, is a list of class special forms that define internal state and procedures. The most important class component is the method. Methods are simply procedures defined inside the class. In order to use the methods, you must use the ask procedure shown above. Each method is referred to by its method name which is the message. Each method can also have corresponding formal parameters. To define a method within a class you have the following form: (method (<method-name> <param 1 >... <param n >) <body>) To create an object, the instantiate procedure must be invoked given the class and the actual parameters needed to fill the instantiation variables. The instantiate procedure has the following form: (instantiate <class> <obj-param 1 >... <obj-param n >)

Page < 3 > The following examples taken from the reader show how to form expressions using the previously covered forms: (define-class (account balance) (method (deposit amount) (set! balance (+ amount balance)) balance) (method (withdraw amount) (if (< balance amount) Insufficient funds (begin (set! balance (- balance amount)) balance))) ) (define Matt-Account (instantiate account 1000)) Internal State There are three types of variables that can be defined inside a class, instantiation variables, instance variables, and class variables. Each one has a special purpose in a class. Instantiation Variables: These are what you define when you first make an object. (define-class (<class-name> <var-name 1 >... <var-name n >)...) Instance Variables: These are bound with the value resulting from the evaluation of the corresponding expression when the object is created. This is a class component. (instance-vars (<var-name 1 > <exp 1 >)... (<var-name n > <exp n >)) Class Variables: These are bound with the value resulting from the evaluation of the corresponding expression when the class is created. This is a class component. (class-vars (<var-name 1 > <exp 1 >)... (<var-name n > <exp n >)) Variables can only be accessed directly within their own class definition 2. For each variable in an object, there is a method created with the same name which returns the variable s value. Class variables can be accessed from both the class and the object because they are shared by both. By using ask, class variables can be returned. This has the following form: (ask <class or object> <var-name>) Remember that var-name must be a quoted symbol since ask is a procedure and not a special form. 2 In the case of inheritance discussed later, a parent class is not considered a part of the child class, so the inherited variables are not directly accessable.

Page < 4 > The Self Object Each object needs a way to access itself to use its own methods. While its variables can be accessed by evaluating Scheme symbols in the normal fashion, methods are not bound to symbols in the same way and must be asked to perform an operation 3. To facilitate this need, a local instance variable, self, is created in each object and is bound to each corresponding object. Within an object, the self variable can be used as shown: (ask self <message> <param 1 >... <param n >) Inheritance An important feature of our OOP paradigm is inheritance. We can reuse class structures as the basis for new, more specific classes. The new class shares the methods of the base classes 4, and can be expanded on to have additional state variables and procedures. This is done by using the parent class component. The parent special form can take as many classes as you want the new class to inherit from. Any conflicting names of methods will be resolved by using the value from the parent closest to the front of the list. This has the following form: (parent (<class-name 1 > <param 1 >... <param k >)... (<class-name n > <param 1 >... <param l >)) In order to access variables related to a parent class, the method must be used because the child only shares method definitions, not variable definitions. The inheritance example from the reader is: (define-class (checking-account init-balance) (parent (account init-balance)) (method (write-check amount) (ask self withdraw (+ amount 0.10)) )) 3 You need ask to use methods because they are not bound to symbols in Scheme s environment like local variables. Instead, they are stored in a separate data structure, and must be looked up there. 4 This is an important distinction from other OOP languages. In other languages, variables are also shared by the child class. This implementation of OOP only shares methods.

Page < 5 > Asking The Usual Method There are times when you have a child class and you need to make some of its methods do something slightly different than its parent's methods. If you want the child class's interface to match the parent's, then you'll need to use the same method names as those used in the parent class. Now if you also need to call the parent's methods instead of the newly redefined methods, you're in trouble if you only have ask because it checks for the child class's methods before checking for the parent class's methods. The usual method call is just like using ask with self except it acts as though the method name provided could not be found in the child class, so it automatically starts checking the parent classes. The example given in the reader is: (define-class (TA) (parent (worker)) (method (work) (usual 'work) '(Let me help you with that box and pointer diagram)) (method (grade-exam) 'A+) ) Notice how the work method was defined in the TA class, yet within the class we needed to access the parent's work method. In this case, if usual hadn't been used, an infinite loop would have been formed. Initialize Procedure The class s initialize procedure is always called at the creation of an object. It can be used to perform operations that need to be done whenever an object is created. A common use of the initialize procedure is to make a list of all the objects of a given class that are in existence (usually stored in a class variable). The example given in the reader is: (define-class (worker) (instance-vars (hunger 0)) (class-vars (all-workers ()) (work-done 0)) (initialize (set! all-workers (cons self all-workers))) (method (work) (set! hunger (1+ hunger)) (set! work-done (1+ work-done)) whistle-while-you-work))

Page < 6 > The Default Method The default-method in a class defines a method that is called when the user asks the object to perform an undefined method. There are two implicit formal parameters to this method, message and args. The message symbol is bound to the method name that wasn t found. The args symbol is bound to those actual parameters (values) that follow after the method name. The example given in the reader is: (define-class (echo-previous) (instance-vars (previous-message first-time)) (default-method (let ((result previous-message)) (set! previous-message message) result))) The downfall of default-method is that it is only called when all other cases are exhausted, so if you have a parent class, the class s default-method is ignored and skipped over when the evaluator decides to look for the missing methods inside the parent class(es). The side-effect is that any default-method in a child class is never used.