61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013

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

SCHEME AND CALCULATOR 5b

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

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

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

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

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

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

Functional Programming. Pure Functional Programming

Administrivia. Simple data types

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

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

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

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

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

Chapter 1. Fundamentals of Higher Order Programming

Lecture #24: Programming Languages and Programs

Functional Programming. Pure Functional Languages

Principles of Programming Languages 2017W, Functional Programming

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

Documentation for LISP in BASIC

Functional programming with Common Lisp

Functional Programming. Pure Functional Languages

Lisp. Versions of LISP

Introduction to Scheme

April 2 to April 4, 2018

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

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

User-defined Functions. Conditional Expressions in Scheme

INTERPRETATION AND SCHEME LISTS 12

Organization of Programming Languages CS3200/5200N. Lecture 11

61A Lecture 28. Friday, November 4

Introduction to Functional Programming

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

Warm-up! CS 3 Final Review. Predict the output. Predict the Output. Predict the output. Predict the output. What is your favorite color?

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

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

INTERPRETATION AND SCHEME LISTS 12

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

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

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

CS 314 Principles of Programming Languages

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

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

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

CS 314 Principles of Programming Languages

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

CSE413 Midterm. Question Max Points Total 100

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

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

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

Scheme Quick Reference

A LISP Interpreter in ML

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

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

Chapter 15 Functional Programming Languages

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

(scheme-1) has lambda but NOT define

CS61A Midterm 2 Review (v1.1)

Scheme Quick Reference

Discussion 4. Data Abstraction and Sequences

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

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

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

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

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Structure and Interpretation of Computer Programs

Functional Programming

CSE 341 Section Handout #6 Cheat Sheet

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

CS 360 Programming Languages Interpreters

Discussion 12 The MCE (solutions)

PROBLEM SOLVING 11. July 24, 2012

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

1.3. Conditional expressions To express case distinctions like

Scheme as implemented by Racket

Programming Languages

Functional programming in LISP

Introductory Scheme. Revision 1

From Syntactic Sugar to the Syntactic Meth Lab:

A Brief Introduction to Scheme (II)

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

Building a system for symbolic differentiation

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

Func%onal Programming in Scheme and Lisp

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CS 314 Principles of Programming Languages. Lecture 16

6.001 Notes: Section 17.5

Functional Programming Languages (FPL)

6.001 Notes: Section 8.1

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

Func%onal Programming in Scheme and Lisp

CPS 506 Comparative Programming Languages. Programming Language Paradigm

FP Foundations, Scheme

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

Computer and Programming: Lab 1

An introduction to Scheme

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

Transcription:

61A LECTURE 18 SCHEME Steven Tang and Eric Tzeng July 24, 2013

What s happening today? We re learning a new language! After you know one language (Python), learning your second (Scheme) is much faster Learn by doing have a sheet of paper ready Solutions in the code supplement for this lecture

Scheme Is a Dialect of Lisp The greatest single programming language ever designed. - Alan Kay, co- inventor of OOP The most powerful programming language is Lisp. If you don't know Lisp (or its variant, Scheme), you don't appreciate what a powerful language is. Once you learn Lisp you will see what is missing in most other languages. - Richard Stallman, founder of the Free SoNware movement Probably my favorite programming language. - Eric Tzeng, CS61A Instructor - Steven Tang, CS61A Instructor h"p://imgs.xkcd.com/comics/lisp_cycles.png

Scheme Fundamentals Scheme programs consist of expressions, which can be: PrimiUve expressions: 2, 3.3, true, +, quotient,... CombinaUons: (quotient 10 2), (not true),... Numbers are self- evaluaung; symbols are bound to values Call expressions have an operator and 0 or more operands > (quotient 10 2) 5 > (quotient (+ 8 7) 5) 3 > (+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6)) 57 quouent names Scheme s built- in integer division procedure (i.e., funcuon) CombinaUons can span muluple lines (spacing doesn t ma"er)

Special Forms A combinauon that is not a call expression is a special form: If expression: And and or: Binding names: New procedures: (if <predicate> <consequent> <alternative>) (and <e1>... <en>), (or <e1>... <en>) (define <name> <expression>) (define (<name> <formal parameters>) <body>) > (define pi 3.14) > (* pi 2) 6.28 > (define (abs x) (if (< x 0) (- x) x)) > (abs - 3) 3 The name pi is bound to 3.14 in the global frame A procedure is created and bound to the name abs

Try it! Translate the following Python functions into Scheme: def one(): return 1 def two(x, y, z): return x + y * z def three(n): if n == 0: return 0 return (n % 10) + 2 * three(n // 10) In Scheme: remainder In Scheme: quotient

Lambda Expressions Lambda expressions evaluate to anonymous procedures (lambda (<formal-parameters>) <body>) Two equivalent expressions: λ (define (plus4 x) (+ x 4)) (define plus4 (lambda (x) (+ x 4))) An operator can be a combinauon too: ((lambda (x y z) (+ x y (square z))) 1 2 3) Evaluates to the add- x- &- y- &- z 2 procedure

Syntactic sugar: defining procedures In Python, lambda expressions are fundamentally different than def statements: The body of a lambda must be a single expression The value of that expression is always returned In Scheme, defining procedures is actually syntactic sugar for a define statement and a lambda expression (define (square x) (* x x)) (define square (lambda (x) (* x x))) Define the function square Define a function and give it the name square

Practice with lambdas Complete the definition of f so that (((f) 3)) evaluates to 1. (define (f)???) Complete the definition of g so that ((g g) g) evaluates to 42. (define g???)

Pairs We can implement pairs funcuonally: (define (pair x y) (lambda (m) (if (= m 0) x y))) (define (first p) (p 0)) (define (second p) (p 1)) Scheme also has built- in pairs that use weird names: cons: Two- argument procedure that creates a pair car: Procedure that returns the first element of a pair cdr: Procedure that returns the second element of a pair A pair is represented by a dot between the elements, all in parens > (cons 1 2) (1. 2) > (car (cons 1 2)) 1 > (cdr (cons 1 2)) 2

Pairs practice Suppose x is the following pair: x 3 1 2 6 7 4 5 How would you select 1 from x? 3? 7? How would you define x in the first place?

Recursive Lists A recursive list can be represented as a pair in which the second element is a recursive list or the empty list Scheme lists are recursive lists: nil is the empty list A non- empty Scheme list is a pair in which the second element is nil or a Scheme list Scheme lists are wri"en as space- separated combinauons > (define x (cons 1 (cons 2 (cons 3 (cons 4 nil))))) > x (1 2 3 4) > (cdr x) (2 3 4) > (cons 1 (cons 2 (cons 3 4))) (1 2 3. 4) Not a well- formed list!

Aside: Booleans and Boolean contexts Boolean constants In Python, we had True and False as our Boolean constants In Scheme, we use #t and #f instead Boolean contexts In Python, most objects were treated like True, but many different objects were treated as False (0,, [], etc.) In Scheme, everything is treated like #t, with the exception of #f itself. (define (length lst) (if (not lst) 0 (+ 1 (length (cdr lst))))) WRONG WRONG WRONG (define (length lst) (if (null? lst) 0 (+ 1 (length (cdr lst)))))

Recursive list practice Write a Scheme function append that takes two lists and returns a single list that contains the values from the first list and the second list, in order: STk> (append (list 1 2 3) (list 4 5 6)) (1 2 3 4 5 6)

Symbolic Programming Symbols are normally evaluated to produce values; how do we refer to symbols? > (define a 1) > (define b 2) > (list a b) (1 2) No sign of a and b in the resulung value QuotaUon prevents something from being evaluated by Lisp > (list 'a 'b) (a b) > (list 'a b) (a 2) QuotaUon can also be applied to combinauons to form lists > (car '(a b c)) a > (cdr '(a b c)) (b c) Symbols are now values

Scheme Lists and Quotation Dots can be used in a quoted list to specify the second element of the final pair > (cdr (cdr '(1 2. 3))) 3 However, dots appear in the output only of ill- formed lists > '(1 2. 3) (1 2. 3) > '(1 2. (3 4)) (1 2 3 4) > '(1 2 3. nil) (1 2 3) 1 2 3 1 2 3 4 nil 1 2 3 nil What is the printed result of evaluaung this expression? > (cdr '((1 2). (3 4. (5)))) (3 4 5)

The Let Special Form Let expressions introduce a new frame, with the given bindings (let ((<name> <exp>)...) <body>) 1! 2! 3! 4! 5! 6! 7! (define (filter fn s) (if (null? s) s (let ((first (car s)) (rest (filter fn (cdr s)))) (if (fn first) (cons first rest) rest)))) > (filter even? '(1 2 3 4 5 6 7)) (2 4 6)

Quick Sort Quick sort algorithm: 1. Choose a pivot (e.g. first element) 2. ParUUon into three pieces: < pivot, = pivot, > pivot 3. Recurse on first and last piece 9 3 1 6 5 8 7 3 1 6 5 8 7 9 1 3 6 5 8 7 (define (filter-comp comp pivot s) (filter (lambda (x) (comp x pivot)) s)) 5 6 8 7 (define (quick-sort s) 7 8 (if (<= (length s) 1) s (let ((pivot (car s))) (append (quick-sort (filter-comp < pivot s)) (filter-comp = pivot s) (quick-sort (filter-comp > pivot s))))))

Turtle graphics STk has built in support for basic 2D graphics! Turtle sits on the canvas As the turtle walks around the canvas, it leaves a trail Images are drawn by issuing commands to the turtle (define (triangle) (forward 100) Move forward (right 120) 100 steps (forward 100) Turn right 120 (right 120) degrees (forward 100) (right 120)) Picture by Jonathan Zander Did we need the last call to right? Why?

The Begin Special Form Begin expressions allow sequencing (begin <exp 1 > <exp 2 >... <exp n >) (define (repeat k fn) (if (> k 0) (begin (fn) (repeat (- k 1) fn)) 'done)) (define (tri fn) (repeat 3 (lambda () (fn) (lt 120)))) (define (sier d k) (tri (lambda () (if (= k 1) (fd d) (leg d k))))) (define (leg d k) (sier (/ d 2) (- k 1)) (penup) (fd d) (pendown))