CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.

Slides:



Advertisements
Similar presentations
CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
1-1 An Introduction to Scheme March Introduction A mid-1970s dialect of LISP, designed to be a cleaner, more modern, and simpler version than.
CS61A Lecture 4 Higher Order Functions Tom Magrino and Jon Kotker UC Berkeley EECS June 21, 2012.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
Administrivia Project 3 Part A due 3/29 (Monday after SB) Part B due 4/5 (a week after)  Everyone with a partner that wants a partner?  Extra Office.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
CS61A Lecture 3 Higher Order Functions Jon Kotker and Tom Magrino UC Berkeley EECS June 20, 2012.
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
ISBN Chapter 15 Functional Programming Languages.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
CS 330 Programming Languages 11 / 13 / 2008 Instructor: Michael Eckmann.
Functional Programming in Scheme and Lisp.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
CS61A Lecture Colleen Lewis. Clicker poll Where do you think you’re learning the most? I assume you’ll learn the most in lab & disc (so.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.
CS61A Lecture Colleen Lewis. Clicker poll Do you feel comfortable posting questions to piazza? A)Yes with my classmates and instructors.
CS314 – Section 5 Recitation 9
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2016.
CS314 – Section 5 Recitation 10
Additional Scheme examples
Functional Programming Languages
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Winter 2013.
CS 326 Programming Languages, Concepts and Implementation
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2017.
6.001 SICP Object Oriented Programming
PPL Lazy Lists.
CS 326 Programming Languages, Concepts and Implementation
Lists in Lisp and Scheme
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Autumn 2017.
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Autumn 2018.
The Metacircular Evaluator
FP Foundations, Scheme In Text: Chapter 14.
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Zach Tatlock Winter 2018.
The Metacircular Evaluator (Continued)
6.001 SICP Further Variations on a Scheme
Explicit Application of Procedures, and Explicit Evaluation
6.001 SICP Variations on a Scheme
List and list operations (continue).
6.001 SICP Interpretation Parts of an interpreter
Common Lisp II.
Lisp.
*Lecture based on notes from SICP
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2019.
Presentation transcript:

CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Review: Dispatch Dictionaries Review: OOP Implementation Scheme, a new language

4 R EVIEW : D ISPATCH D ICTIONARIES Idea: We will allow ourselves one kind of data structure. In particular, we will represent an object by a dispatch dictionary, where the messages are the keys.

5 R EVIEW : D ISPATCH D ICTIONARIES def make_pair(first, second): pair_dict = { ‘first’ : first, ‘second’: second } return pair_dict How do we create and use “pair objects” now?

6 D ISPATCH D ICTIONARIES >>> def make_pair(first, second):... >>> p = make_pair(1, 2) G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p pair_dict

7 D ISPATCH D ICTIONARIES >>> p[‘first’] 1 G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p pair_dict

8 D ISPATCH D ICTIONARIES >>> p[‘first’] = 3 G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p 3 pair_dict

9 R EVIEW : OOP I MPLEMENTATION : I NHERITANCE Modified solution: def make_class(attributes={}, base_class=None): def get_value(name): if name in attributes: return attributes[name] elif base_class is not None: return base_class[‘get’](name) def set_value(name, value): attributes[name] = value cls = {‘get’: get_value, ‘set’: set_value} return cls To find the value of a class attribute… … check if it is already in the dictionary of attributes. Otherwise, if there is a parent class, check if the parent class has the class attribute. A class is still a dictionary! The two new messages get and set allow us to use the general getter and setter functions.

10 R EVIEW : OOP I MPLEMENTATION : O BJECTS Just as we did with classes, we use dictionaries to represent objects: def make_instance(cls): def get_value(name): if name in attributes: return attributes[name] else: return cls[‘get’](name) def set_value(name, value): attributes[name] = value attributes = {} instance = {‘get’: get_value, ‘set’: set_value} return instance To find the value of an instance attribute… … check if it is already in the dictionary of attributes. Otherwise, check if the class has a value for the attribute. Dictionary of instance attributes An instance is a dictionary! The two messages get and set allow us to use the general getter and setter functions. What class is this object an instance of?

11 R EVIEW : OOP I MPLEMENTATION : O BJECTS def make_instance(cls): def get_value(name): if name in attributes: return attributes[name] else: value = cls[‘get’](name) return bind_method(value, instance) All the methods are defined in the class. We might get one of these: if we do, bind the first argument to the current instance to produce a bound method for the instance.

12 R EVIEW : OOP I MPLEMENTATION : O BJECTS def bind_method(value, instance): if callable(value): def method(*args): return value(instance, *args) return method else: return value If the value provided is callable (for example, a function),... … make the new bound method… … where the first argument is bound to the instance given, and all the other arguments remain the same… … and return this bound method. If the value provided is not callable, return it as is. callable is a predicate that checks if the argument provided can be called with arguments.

13 R EVIEW : OOP I MPLEMENTATION : I NSTANTIATION AND I NITIALIZATION We add an extra message that our classes can understand, which will allow us to create new objects: def make_class(attributes={}, base_class=None):... def new(*args): return init_instance(cls, *args) cls = {‘get’: get_value, ‘set’: set_value, ‘new’: new} return cls

14 R EVIEW : OOP I MPLEMENTATION : U SAGE def make_pokemon_class(): def __init__(self, name, owner, hp): self[‘set’](‘name’, name) self[‘set’](‘owner’, owner) self[‘set’](‘hp’, hp) def increase_hp(self, amount): old_hp = self[‘get’](‘hp’) self[‘set’](‘hp’, old_hp + amount)... return make_class({‘__init__’: __init__, ‘increase_hp’: increase_hp,...})

15 R EVIEW : OOP I MPLEMENTATION : U SAGE >>> Pokemon = make_pokemon_class() >>> ashs_pikachu = Pokemon[‘new’](‘Pikachu’, ‘Ash’, 300) >>> ashs_pikachu[‘get’](‘hp’) 300 >>> ashs_pikachu[‘get’](‘owner’) ‘Ash’ >>> ashs_pikachu[‘get’](‘increase_hp’)(50) >>> ashs_pikachu[‘get’](‘hp’) 350

16 A NNOUNCEMENTS : M IDTERM 2 Midterm 2 is on Wednesday, July 25. – Where? 2050 VLSB. – When? 7PM to 9PM. – How much? Material covered until, and including, July 19. Closed book and closed electronic devices. One 8.5” x 11” ‘cheat sheet’ allowed. Group portion is 15 minutes long. If you have a conflict, please let us know by the end of today, July 23.

17 A NNOUNCEMENTS Homework 10 is due Today. Project 3 is due Thursday, July 26. Homework 11 is due Friday, July 27. – This will be released sometime tonight. Please ask for help if you need to. There is a lot of work in the weeks ahead, so if you are ever confused, consult (in order of preference) your study group and Piazza, your TAs, and Jom. Don’t be clueless!

18 S CHEME : A D IALECT OF L ISP The language you will implement for Project 4. One of the oldest languages still in use today! Easiest way to learn Scheme is to start by seeing some examples and then play with it, so that’s what most of today will be.

19 S CHEME : S IMPLE E XAMPLES STk> 5 5 STk> ‘hello hello STk> ‘(hello tom) (hello tom) STk> (+ 5 7) 12 STk> (* 3 22) 66 STk> (= 3 22) #f STk> (= 3 3) #t STk> (equal? ‘foo ‘bar) #f STk> (equal? ‘foo ‘foo) #t

20 S CHEME : S IMPLE E XAMPLES STk> (if (= 3 3) ‘true ‘false) true STk> (if (= 3 4) ‘true) okay STk> (first ‘word) w STk> (butfirst ‘word) ord STk> (last ‘word) d STk> (butlast ‘word) wor STk> (word ‘race ‘car) racecar STk evaluates Scheme expressions to okay if there is no value to the expression.

21 S CHEME : S IMPLE E XAMPLES STk> (cond ((= 5 0) ‘zero) ((= (remainder 5 2) 0) ‘even) (else ‘odd)) odd STk>

Scheme: Prefix Notation In Python: In Scheme (+ 4 7) Scheme uses prefix notation where all operations appear before the expressions used by the operation. There is absolutely no exceptions to this notation. This makes the language much simpler, since we don’t have a bunch of different special cases for each type of operation. Notice that the parentheses go BEFORE the function or operation.

23 S CHEME : V ARIABLES STk> (define toms-number 5) toms-number STk> toms-number 5 STk> y *** Error: unbound variable: y... STk> (+ toms-number 66) Variable names can have hyphens in Scheme

24 S CHEME : F UNCTIONS STk> (define (square x) (* x x)) square STk> (square 5) 25 STk> square #[closure arglist=(x) 23a8a8] Notice that we didn’t have to say return or anything like that! In Scheme, every function MUST return a value. This is always the last expression of the body.

25 S CHEME : F UNCTIONS STk> (lambda (x) (+ x 1)) #[closure arglist=(x) 23bbc8] STk> ((lambda (x) (* x x)) 3) 9 STk> (define (call-with-2 fn) (fn 2)) call-with-2 STk> (call-with-2 (lambda (x) (+ x 1))) 3 STk> (lambda () 3) #[closure arglist=() blahblahblah] STk> ((lambda () 3)) 3 Scheme has lambdas! Unlike Python, anything you can do in a named function you can also do in a lambda.

26 S CHEME : R EPETITION STk> (define (fact n) (if (<= n 1) 1 (* n (fact (- n 1))))) fact STk> (fact 5) 120 Traditionally, even if the version of Scheme you’re running has loops, it’s much more common to stick to recursion.

27 S CHEME : M ORE E XAMPLES STk> (define (twice f) (lambda (x) (f (f x)))) twice STk> (((twice (twice twice)) 1+) 0) 16 STk> (define (make-adder x) (lambda (y) (+ x y))) make-adder STk> ((make-adder 7) 22) 29

28 B REAK : S OME L ISP C OMICS

29 S CHEME : P AIRS AND L ISTS STk> (cons 2 5) (2. 5) STk> (list ) ( ) STk> (car ‘(1 2 3)) 1 STk> (cdr ‘(1 2 3)) (2 3) STk> (cons 1 ‘()) (1) STk> (cons 1 (cons 2 (cons 3 ‘()))) (1 2 3)

30 S CHEME : L ISTS STk> (append ‘(1 2 3) ‘(4 5 6)) ( ) STk> (define (map fn lst) (if (null? lst) ‘() (cons (fn (car lst)) (map fn (cdr lst))))) STk> (map (lambda (x) (* x 5)) ‘(1 2 3)) ( ) STk> (map (lambda (x) (* x 22)) ‘(1 2 3)) ( )

31 P RACTICE : S CHEME What does each expression evaluate to? STk> (square (square 5)) ??? STk> ‘(square 5) ??? STk> (cons (car ‘(3. 4)) (cdr ‘(5. 6))) ??? STk> (cons (car ‘(3. 4)) (cdr ‘(5 6))) ???

32 P RACTICE : S CHEME What does each expression evaluate to? STk> (square (square 5)) 625 STk> ‘(square 5) (square 5) STk> (cons (car ‘(3. 4)) (cdr ‘(5. 6))) (3. 6) STk> (cons (car ‘(3. 4)) (cdr ‘(5 6))) (3 5 6)

33 P RACTICE : S CHEME Write the function filter which takes a predicate and a list and produces a new list only including the elements for which the predicate is true. STk> (filter (lambda (x) (= (remainder x 2) 0)) ‘( )) ( ) STk> (filter (lambda (x) (< x 5)) ‘( )) (1 2 3)

34 C ONCLUSION Scheme: It’s awesome, it’s simple, it’s what you’re implementing in project 4. Preview: We will start to talk about how we implement an interpreter.