Introduction to Scheme

Similar documents
Functional Programming. Pure Functional Programming

Essentials of Programming Languages Language

Essentials of Programming Languages Language

Functional Programming. Pure Functional Languages

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

Scheme Quick Reference

Functional Programming. Pure Functional Languages

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

Scheme Quick Reference

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

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

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

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

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

An Explicit-Continuation Metacircular Evaluator

Organization of Programming Languages CS3200/5200N. Lecture 11

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

Project 2: Scheme Interpreter

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

An Introduction to Scheme

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

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

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

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

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

ALISP interpreter in Awk

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

A Brief Introduction to Scheme (II)

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

Functional programming with Common Lisp

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

LECTURE 16. Functional Programming

6.001: Structure and Interpretation of Computer Programs

Functional Programming

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

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

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Lecture #24: Programming Languages and Programs

Principles of Programming Languages

CSCC24 Functional Programming Scheme Part 2

CSC 533: Programming Languages. Spring 2015

Functional Programming. Big Picture. Design of Programming Languages

Documentation for LISP in BASIC

1.3. Conditional expressions To express case distinctions like

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

How to Design Programs Languages

Chapter 1. Fundamentals of Higher Order Programming

Functional Programming Lecture 1: Introduction

A Small Interpreted Language

CSc 520 Principles of Programming Languages

CS 314 Principles of Programming Languages

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

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

User-defined Functions. Conditional Expressions in Scheme

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

Imperative, OO and Functional Languages A C program is

Building a system for symbolic differentiation

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

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

CS 360 Programming Languages Interpreters

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

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

Building a system for symbolic differentiation

Overview. CS301 Session 3. Problem set 1. Thinking recursively

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

Programming Languages Third Edition

Evaluating Scheme Expressions

Artificial Intelligence Programming

Scheme: Expressions & Procedures

Lambda Calculus see notes on Lambda Calculus

FP Foundations, Scheme

Building up a language SICP Variations on a Scheme. Meval. The Core Evaluator. Eval. Apply. 2. syntax procedures. 1.

COP4020 Programming Assignment 1 - Spring 2011

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

University of Massachusetts Lowell

CS 314 Principles of Programming Languages. Lecture 16

Functional Languages. Hwansoo Han

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

This book is licensed under a Creative Commons Attribution 3.0 License

Programming Languages

Administrivia. Simple data types


Functional Programming Languages (FPL)

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

Programming Language Concepts, cs2104 Lecture 04 ( )

4/19/2018. Chapter 11 :: Functional Languages

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

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

Vectors in Scheme. Data Structures in Scheme

Parsing. Zhenjiang Hu. May 31, June 7, June 14, All Right Reserved. National Institute of Informatics

Introduction to lambda calculus Part 3

Revised 5 Report on the Algorithmic Language Scheme

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

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Programming Languages

CS61A Midterm 2 Review (v1.1)

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

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Transcription:

How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free Grammars. Semantics: What the programs mean. Informally, using English Operationally, showing an interpreter Other: Axiomatic, Denotational, Look at R5RS for how this is done formally CS 421 Lecture 2 & 3: Scheme 2 Context Free Grammars A (context-free) grammar consists of four parts: 1. A set of tokens or terminals. These are the atomic symbols in the language. 2. A set of non-terminals. These represent the various concepts in the language 3. A set of rules called productions mapping the non-terminals to groups of tokens. 4. A start non-terminal Example: English Language Terminals Non-Terminals Productions Main Non-Terminal CS 421 Lecture 2 & 3: Scheme 3 CS 421 Lecture 2 & 3: Scheme 4 Example: English Language Terminals Words of the language Non-Terminals Productions Main Non-Terminal Example: English Language Terminals Words of the language Non-Terminals sentences, verbs, nouns, adverbs, complex, noun phrases,... Productions Main (Start) Non-Terminal CS 421 Lecture 2 & 3: Scheme 5 CS 421 Lecture 2 & 3: Scheme 6 1

Example: English Language Terminals Words of the language Non-Terminals sentences, verbs, nouns, adverbs, complex, noun phrases,... Productions Any guesses Main Non-Terminal sentence Backus Naur Form BNF non-terminals are enclosed in the symbols < > < > represents the empty string Example: <string> ::= < > <char><string> <char> ::= a b c... ::= should be read as can be should be read as or Sometimes is used for ::= CS 421 Lecture 2 & 3: Scheme 7 CS 421 Lecture 2 & 3: Scheme 8 A Grammar for Core Scheme <expression> <constant> <identifier> (if <expression> <expression> <expression>) (define <identifier> <expression>) (quote <expression>) (begin <expression>... <expression>) (lambda <formals> <body>) <procedure call> Grammar continued <constant> <boolean> <number> <character> <string> <formals> (<variable>*) <variable> <(<variable 1 > <variable n >. <variable>) <body> <expression> <procedure call> (<operator> <operand>*) <operator> <expression> <operand> <expression> And productions for <boolean>, <number>, <character>, <string> CS 421 Lecture 2 & 3: Scheme 9 CS 421 Lecture 2 & 3: Scheme 10 Syntactic Keywords of Scheme Control: quote, lambda, if, define, begin. Predicates: equal? null? zero?... Recognizers: integer? boolean? string? pair? list? procedure?... Lists: car cdr cons... An Overview of Scheme R-E-P Interacting via the Read-Eval-Print loop Atomic Data booleans, numbers, symbols, characters & strings... Expressions What are they? and how are they evaluated. Conditionals if and syntactic sugar (macros): not, and, or, cond. Recognizers & Predicates CS 421 Lecture 2 & 3: Scheme 11 CS 421 Lecture 2 & 3: Scheme 12 2

Overview of Scheme (Contd.) Overview of Scheme (contd.) Functions lambda, let, let* Definitions what they are and what they look like. Lists & quote what they look like, including the empty list List Manipulation Constructing and deconstructing lists: car, cdr, cons Recursive Definition what is it, some examples, and how it works. Recursion vs Iteration translating a while into a recursive function (tail recursion) List Processing some world famous list functions Functionals functions of function e.g., mapping & sorting CS 421 Lecture 2 & 3: Scheme 13 CS 421 Lecture 2 & 3: Scheme 14 Binding Functional Language Pattern Matching what is it & how is it done. Notions of Equality eq? and its many relations. Data Mutation & Scheme Actors setcar!, setcdr! and the sieve of erasthones Functions are first-class values in Scheme.. Functions can be used as arguments Functions can be returned as values Functions can be bound to variables and stored in data structures Important Note: No mutations (assignments) may be used in the first couple of MPs Scheme is not a strictly functional language: bindings of variables can be mutated. We will avoid this for now. CS 421 Lecture 2 & 3: Scheme 15 CS 421 Lecture 2 & 3: Scheme 16 Talking to Scheme > (define cell (cons + *)) > 3434 3434 > (integer? 2345) #t > (+ 1 2 3 4) 10 > (define + *) #<unspecified> > (+ 1 2 3 4) 24 > + + #<primitive-procedure *> > (lambda (x) (* x x)) (lambda (a1) ) #<CLOSURE (x) (* x x)> ((lambda (x) (* x x)) 12) 144 > cell (cons + *) > (procedure? (car cell)) true > ((cdr cell) 5 5) 25 CS 421 Lecture 2 & 3: Scheme 17 CS 421 Lecture 2 & 3: Scheme 18 3

Atomic Data Booleans the truth values: #f #t Numbers integer rational real complex number Symbols or identifiers Used as variables to name values Characters & Strings #\a ;lower case letter a #\space ; the preferred way to write a space #\newline ; the newline character "this is a typical string Notes Booleans, numbers, characters are constants. Symbols (other than predefined functions) must be given a value. All these data types are disjoint, i.e. nothing can be both a this and a that. CS 421 Lecture 2 & 3: Scheme 19 CS 421 Lecture 2 & 3: Scheme 20 Expressions Constants, Symbols and Data Lists Special forms Application of a function to given arguments <exp> ::= (<exp> <exp>... <exp>) Stands for: <function application> ::= (<fun> <arg1>... <argn>) Examples > (* 3 4 (+ 2 3)) 60 > (*) 1 > ((lambda (x) (* x 4)) 4) 16 > ((car (cons + *)) 7 3) 10 CS 421 Lecture 2 & 3: Scheme 21 CS 421 Lecture 2 & 3: Scheme 22 Notes Function application is call-by-value. Each <arg> is evaluated, as is the <fun>. The order of evaluation is not specified. Some functions have no arguments. ( ) is not a function application, its the empty list. Sequencing (begin <exp>... <exp>) evalutes the expressions <exp> from left right returns the value of the rightmost expression. >(begin (write "a") (write "b") (write "c") (+ 2 3)) "a""b""c"5 writes "a", "b" and "c" out to the screen, in that order. evaluates to 5. CS 421 Lecture 2 & 3: Scheme 23 CS 421 Lecture 2 & 3: Scheme 24 4

Lists (list? x) evaluates to #t if and only if x is/names a list. Otherwise it evaluates to #f. ( ) ;the empty list (list? ( )) (null? ()) (null? x) (this is a list with a very deep ((((((((((((((((((end))))))))))))))))))) Lists and Expressions Scheme expressions are lists Expressions are evaluated How to say something is a list rather than an expression? Use the special form quote: > (quote <expression>) evaluates to the list or scheme object expression. No evaluation of expression takes place. Abbreviated as: <expression> CS 421 Lecture 2 & 3: Scheme 25 CS 421 Lecture 2 & 3: Scheme 26 Examples > (+ 1 2) > (+ (* 3 4) 1 2) >(procedure? +) >(procedure? +) >(symbol? +) >(symbol? +) Notes Notation Convention Recognizers end with a? There is also a! convention -- used for something different Constants Convention Constants such as booleans, strings, characters, and numbers do not need to be quoted. Quoted Lists A quoted list is treated as a constant. It is an error to alter one. Nested Lists Lists may contain lists, which may contain lists, which may contain lists... CS 421 Lecture 2 & 3: Scheme 27 CS 421 Lecture 2 & 3: Scheme 28 List Manipulation Operations cons is the list constructor car gets the first element of a list. Its name comes from: Contents of the AddressRegister. cdr gets the rest of a list. Its name comes from: Contents of the Decrement Register. Names inherited from the first implementation of Lisp on IBM 704 back in 1958. Examples 1. (cons 1 ()) evaluates to (1) 2. (cons 5 (1 2 3 4)) 3. (cons (1 2 3 4) (5)) 4. (car (a b c d)) 5. (cdr (a b c d)) 6. (caar ((1) 2 3 4)) 7. (cddr (a b c d)) 8. (cdddr (a b c d)) 9. (cddddr (a b c d)) CS 421 Lecture 2 & 3: Scheme 29 CS 421 Lecture 2 & 3: Scheme 30 5

Notes Lisp Manipulation Axioms 1. (car ()) is undefined, as is (cdr ()). 2. (pair? <list>) => #t when <list> is non-empty. 3. (pair? ()) 4. Any composition of cars and cdrs of length upto length 4 is valid, car cdr caar cdar cadr cddr caaar cdaar cadar caddr cdadr cddar cdddr caaaar... cddddr 1. (car (cons <a> <d>)) is <a> 2. (cdr (cons <a> <d>)) is <d> 3. If <list> is a list, then (cons (car <list>) (cdr <list>)) is equal? to <list> Question: How many operations in this last line? CS 421 Lecture 2 & 3: Scheme 31 CS 421 Lecture 2 & 3: Scheme 32 List Recursion Check if it is a list (list? ) Repeatedly apply cdr till you reach the end of the list Use (null? ) to check if it empty before deconstructing Use (cons ) to build a list Use (cdr ) to walk through list Think Recursively! Write a function, F, which when given a list <list> produces a new list, obtained by adding 1 to every number in the <list> (F (a 1 b 2 c 3 d 4 e 5)) (F (a 2 b 3 c 4 d 5 e 6)) CS 421 Lecture 2 & 3: Scheme 33 CS 421 Lecture 2 & 3: Scheme 34 Base Case and Induction If <list> is the empty list, then what should (F <list>) be? If I know what (car <list>) is, and I also know what (F (cdr <list>)) is, do I know what (F <list>) should be? The Answers (F ( )) should just be ( ) if (car <list>) is a number (F <list>) should be (cons (+ 1 (car <list>)) (F (cdr <list>))) if (car <list>) is not a number (F <list>) should be (cons (car <list>) (F (cdr <list>))) CS 421 Lecture 2 & 3: Scheme 35 CS 421 Lecture 2 & 3: Scheme 36 6

The Code (define F > (F '(a 1 b 2 c 3 d 4 e 5)) (lambda (l) (a 2 b 3 c 4 d 5 e 6) (if (null? l) ( ) (if (number? (car l)) (cons (+ 1 (car l)) (F (cdr l))) (cons (car l) (F (cdr l))))))) Tracing Procedures > (trace F) (F) > (F '(1 2 3 4)) (F (1 2 3 4)) (F (2 3 4)) (F (3 4)) (F (4)) (F ()) () (5) (4 5) (3 4 5) (2 3 4 5) (2 3 4 5) CS 421 Lecture 2 & 3: Scheme 37 CS 421 Lecture 2 & 3: Scheme 38 Understanding cons cons creates a new pair each time it is called! eq? on pairs returns true if and only if the two pairs are the same pairs Box Diagrams List notation Pair notation (a b c d) (a. (b. (c. (d. ()))) (define a (cons 3 ())) (define b (cons 3 ())) > (eq? a a) #t > (eq? a b) #f > (eq? () ()) #t > (eq? (car a) (car b)) #t (a (b c) d) (a. ((b. (c. ())). (d. ())))) CS 421 Lecture 2 & 3: Scheme 39 CS 421 Lecture 2 & 3: Scheme 40 Other List Operations append takes two or more lists and constructs a new list with all of their elements: >(append (a b) (c d)) (a b c d) >(list '(a b) '(c d)) ((a b) (c d)) Implementing append append is syntactic sugar provided by Scheme Here is how it could be defined for two elements: > (define my-app (lambda (lis1 lis2) (if (null? lis1) l2 (cons (car lis1) (my-app (cdr lis1) lis2))))) > (my-app '(1 2 3) '(4 5 6)) (1 2 3 4 5 6) Beware when you mutate bindings and pass lists! lis2 is reused! CS 421 Lecture 2 & 3: Scheme 41 CS 421 Lecture 2 & 3: Scheme 42 7

Pairs Pairs are a derived data type Values: (datum. datum) Operations: cons, car, cdr, pair?, eq? Lists are internally represented as pairs (a b c d) (a. (b. (c. (d. ()))) (a (b c) d) (a. ((b. (c. ())). (d. ())))) Box Diagrams: Recall that pairs are represented by boxes with car and cdr fields. LHS of dot is car and RHS is cdr Pairs can be shared (define c (1. a)) (define d (cons 2 c)) (define e (cons 2 c)) (eq? d e) #f (eq? (cadr d) (cadr e)) #t CS 421 Lecture 2 & 3: Scheme 43 CS 421 Lecture 2 & 3: Scheme 44 Vectors Vectors are a derived type Provide random access instead of sequential access to elements >(define v1 (vector 1 (+ 1 1))) >v1 #2 (1 2) >(define v2 (vector v1 v1)) >v2 #2 (#0=#2 (1 2)) > (vector-ref v1 0) 1 > (vector-ref (vector-ref v2 1) 1) 2 > (vector-length v2) 2 (vector->list v2) (#0=#2(1 2) #0#) CS 421 Lecture 2 & 3: Scheme 45 Higher-Order Procedures Composition of functions. If g : A B and f : B C then f g : A C is defined as (f g) (x) = f (g (x)) > (define compose (lambda (f g) (lambda (x) (f (g x))))) > ((compose car cdr) (a b c d)) b CS 421 Lecture 2 & 3: Scheme 46 Higher-order Procedure (contd.) ((compose list (compose cdr cdr)) (a b c d)) ((c d)) >(define car-of-cdr (compose car cdr)) >(car-of-cdr (a b c d)) b Curried Functions Multiple argument function can be represented by single argument functions. Let f : A x B C Define curry : (A x B) (A B C) curry(f)(x)(y) = f(x,y) Curry is a bijection. CS 421 Lecture 2 & 3: Scheme 47 CS 421 Lecture 2 & 3: Scheme 48 8

Defining Curry Variable Arity Procedures > (define curry (lambda (f) (lambda (x) (lambda (y) (f x y))))) > (((curry +) 1) 2) 3 (define add1 ((curry +) 1)) (add1 4) 5 Examples: list, vector, string, +, *,... Variable arity procedures can be defined as (lambda formal body) Formal: A single variable. Scheme binds all arguments into a list Body: An expression > ((lambda x x) 1 2 3) (1 2 3) > (define my-list (lambda x x)) > (my-list 1 2 3 4) (1 2 3 4) CS 421 Lecture 2 & 3: Scheme 49 CS 421 Lecture 2 & 3: Scheme 50 Variable Arity Procedure Example Local binding Define plus which complains if 0 arguments, takes 1 or 2 arguments, ignores more arguments. >(define plus (lambda lst (if (null? lst (write "wrong number of arguments") (if (null? (cdr lst)) (car lst) (+ (car lst) (cadr lst)))))) > (plus) "wrong number of arguments > (plus 1) 1 > (plus 2 3) 5 > (plus 2 3 4) 5 More syntactic sugar >(let ((x 11) (y 12)) (+ x y)) 33 Is equivalent to: (((lambda (x) (lambda (y) (+ x y))) 11) 12) More complicated with recursion in the bindings CS 421 Lecture 2 & 3: Scheme 51 CS 421 Lecture 2 & 3: Scheme 52 Example: Finding Roots Finding roots of equation f(x)=0, where f is continuous Given points f(a)<0<f(b), f must have at least one zero between a and b. Compute midpoint x of a and b, if f(x)>0, search between f(a) and f(x), otherwise between f(x) and f(b). See, Abelson and Sussman, The Structure and Interpretation of Computer Programs. Search for zero-crossing (Scheme code) (define search (lambda (f neg-point pos-point) (let ((midpoint (average neg-point pos-point))) (if (close-enough? neg-point pos-point) midpoint (let ((test-value (f midpoint))) (cond ((positive? test-value) (search f neg-point midpoint)) ((negative? test-value) (search f midpoint pos-point)) (else midpoint))))))) (define close-enough? (lambda (x y) (< (abs (- x y)).001))) CS 421 Lecture 2 & 3: Scheme 53 CS 421 Lecture 2 & 3: Scheme 54 9

Example: Derivatives References (An approximation to) the derivative of a function is defined by: f ( x + dx) f ( x) Df ( x) = dx (define derivative (lambda (f dx) (lambda (x) (/ ( (f (+ x dx)) (f x)) dx))) An Introduction to Scheme and its Implementation http://www.federated.com/~jim/schintro-v14/schintro_toc.html Structure and Interpretation of Computer Programs http://mitpress.mit.edu/sicp/full-text/book/book.html Revised5 Report on the Algorithmic Language Scheme http://www.schemers.org/documents/standards/r5rs/ CS 421 Lecture 2 & 3: Scheme 55 CS 421 Lecture 2 & 3: Scheme 56 10