How do you describe them

Introduction to Scheme { A language is described by specifying its syntax and semantics { Syntax: The rules for writing programs. z We will use Context Free Grammars. Gul Agha { Semantics: What the programs mean. z Informally, using English CS 421 z Operationally, showing an interpreter Fall 2006 z Other: Axiomatic, Denotational, … { Look at R5RS for how this is done formally

CS 421 Lecture 2 & 3: Scheme 2

Context Free Grammars Example: English Language

A (context-free) grammar consists of four { Terminals parts: 1. A set of tokens or terminals. These are the atomic symbols in the language. { Non-Terminals 2. A set of non-terminals. These represent the various concepts in the language 3. A set of rules called productions { Productions mapping the non-terminals to groups of tokens. { 4. A start non-terminal Main Non-Terminal

CS 421 Lecture 2 & 3: Scheme 3 CS 421 Lecture 2 & 3: Scheme 4

Example: English Language Example: English Language

{ Terminals { Terminals z Words of the language z Words of the language { Non-Terminals { Non-Terminals z sentences, verbs, nouns, adverbs, complex, noun phrases, ..... { Productions { Productions

{ Main Non-Terminal { Main (Start) Non-Terminal

CS 421 Lecture 2 & 3: Scheme 5 CS 421 Lecture 2 & 3: Scheme 6

1 Example: English Language Backus Naur Form

{ Terminals { BNF non-terminals are enclosed in the z Words of the language symbols < … > { Non-Terminals { < > represents the empty string z sentences, verbs, nouns, adverbs, { Example: complex, noun phrases, ..... ::= < > | { Productions ::= a | b | c | ..... z Any guesses ::= should be read as can be { Main Non-Terminal | should be read as or z sentence Sometimes Æ is used for ::=

CS 421 Lecture 2 & 3: Scheme 7 CS 421 Lecture 2 & 3: Scheme 8

A Grammar for Core Scheme Grammar continued Æ Æ | | | | | (if ) | (define ) Æ (*) | (quote ) | | <(. ) | (begin ... ) 1 n | (lambda ) Æ | Æ ( *) Æ Æ

And productions for , , ,

CS 421 Lecture 2 & 3: Scheme 9 CS 421 Lecture 2 & 3: Scheme 10

Syntactic Keywords of Scheme An Overview of Scheme

{ Control: quote, lambda, if, define, { R-E-P begin. z Interacting via the Read-Eval-Print loop { Atomic Data { Predicates: equal? null? zero? z booleans, numbers, symbols, characters & ... strings ... { Expressions { Recognizers: integer? boolean? z What are they? and how are they evaluated. string? pair? list? procedure? ... { Conditionals { Lists: car cdr ... z 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 { Recursive Definition z lambda, let, let* z what is it, some examples, and how it works. { Definitions { Recursion vs Iteration z what they are and what they look like. z translating a while into a recursive function (tail recursion) { Lists & quote z what they look like, including the empty list { List Processing z some world famous list functions { List Manipulation z Constructing and deconstructing lists: car, cdr, { Functionals cons z 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 Functions are first-class values in Scheme.. z what is it & how is it done. { Functions can be used as arguments { Notions of Equality { Functions can be returned as values z eq? and its many relations. { Functions can be bound to variables and { Data Mutation & Scheme Actors stored in data structures z setcar!, setcdr! and the sieve of erasthones

Important Note: No mutations Scheme is not a strictly functional (assignments) may be used in the first language: bindings of variables can be couple of MPs 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 > (+ 1 2 3 4) > cell 3434 24 (cons + *) > (integer? 2345) > + #t + # > (procedure? (car cell)) > (+ 1 2 3 4) > (lambda (x) (* x x)) true 10 (lambda (a1) …) # > (define + *) > ((cdr cell) 5 5) # ¾ ((lambda (x) (* x x)) 12) 144 25

CS 421 Lecture 2 & 3: Scheme 17 CS 421 Lecture 2 & 3: Scheme 18

3 Atomic Data Notes

{ Booleans { Characters & Strings { Booleans, numbers, characters are z the truth values: z #\a #f #t constants. ;lower case letter a { Numbers z #\space ; the preferred { Symbols (other than predefined z integer way to write a space functions) must be given a value. z rational z #\newline z real ; the newline { All these data types are disjoint, i.e. z complex number character nothing can be both a this and a { Symbols or z "this is a typical string“ identifiers that. z Used as variables to name values

CS 421 Lecture 2 & 3: Scheme 19 CS 421 Lecture 2 & 3: Scheme 20

Expressions Examples

{ Constants, Symbols and Data > (* 3 4 (+ 2 3)) { Lists 60 z Special forms > (*) z Application of a function to given arguments 1 ::= ( ... ) > ((lambda (x) (* x 4)) 4) Stands for: ::= 16 ( ... ) > ((car (cons + *)) 7 3) 10

CS 421 Lecture 2 & 3: Scheme 21 CS 421 Lecture 2 & 3: Scheme 22

Notes Sequencing

(begin ..... ) { Function application is call-by-value. { evalutes the expressions from left right Each is evaluated, as is the { returns the value of the rightmost expression. . >(begin (write "a") (write "b") { The order of evaluation is not (write "c") (+ 2 3)) specified. "a""b""c"5 { Some functions have no arguments. z writes "a", "b" and "c" out to the screen, in { ( ) is not a function application, its that order. the empty list. z evaluates to 5.

CS 421 Lecture 2 & 3: Scheme 23 CS 421 Lecture 2 & 3: Scheme 24

4 Lists Lists and Expressions

¾ (list? x) { Scheme expressions are lists ¾ evaluates to #t if and only if x is/names a list. { Expressions are evaluated ¾ Otherwise it evaluates to #f. { How to say something is a list rather than an expression? ¾ ( ) ;the empty list { Use the special form quote: ¾ (list? ( )) > (quote ) ¾ (null? ()) z evaluates to the list or scheme object expression. ¾ (null? x) z No evaluation of expression takes place. ¾ (this is a list with a very deep z Abbreviated as: ((((((((((((((((((end))))))))))))))))))) ’

CS 421 Lecture 2 & 3: Scheme 25 CS 421 Lecture 2 & 3: Scheme 26

Examples Notes

{ Notation Convention >’(+ 1 2) z Recognizers end with a ? z There is also a ! convention -- used for something different >’(+ ’(* 3 4) 1 2) { Constants Convention z Constants such as booleans, strings, characters, and numbers do not need to be quoted. >(procedure? ’+) { Quoted Lists >(procedure? +) z A quoted list is treated as a constant. It is an error to alter one. >(symbol? ’+) { Nested Lists >(symbol? +) z 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 Examples

{ cons is the list constructor 1. (cons 1 ()) evaluates to (1) { car gets the first element of a list. 2. (cons 5 ’(1 2 3 4)) z Its name comes from: 3. (cons ’(1 2 3 4) ’(5)) Contents of the AddressRegister. 4. (car ’(a b c d)) { cdr gets the rest of a list. 5. (cdr ’(a b c d)) z Its name comes from: 6. (caar ’((1) 2 3 4)) Contents of the Decrement Register. 7. (cddr ’(a b c d)) { Names inherited from the first implementation of 8. (cdddr ’(a b c d)) Lisp on IBM 704 back in 1958. 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 ()). 1. (car (cons )) is 2. (pair? ) => #t when is non-empty. 3. (pair? ()) 2. (cdr (cons )) is 4. Any composition of cars and cdrs of length upto 3. If is a list, then length 4 is valid, z car cdr (cons (car ) (cdr )) z caar cdar cadr cddr z caaar cdaar cadar caddr cdadr cddar cdddr is equal? to z caaaar ...... cddddr

Question: How many operations in this last line?

CS 421 Lecture 2 & 3: Scheme 31 CS 421 Lecture 2 & 3: Scheme 32

List Recursion Think Recursively!

{ Check if it is a list (list? …) Write a function, F, which when { Repeatedly apply cdr till you reach given a list produces a the end of the list new list, obtained by adding 1 { Use (null? …) to check if it empty to every number in the before deconstructing { Use (cons …) to build a list ¾ (F ’(a 1 b 2 c 3 d 4 e 5)) { Use (cdr …) to walk through list (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 The Answers

{ If is the empty list, then { (F ’( )) should just be ( ) what should (F ) be? { if (car ) is a number { If I know what (car ) is, and I (F ) should be also know what (F (cdr )) is, (cons (+ 1 (car )) (F (cdr do I know what (F ) should ))) be? { if (car ) is not a number (F ) should be (cons (car ) (F (cdr )))

CS 421 Lecture 2 & 3: Scheme 35 CS 421 Lecture 2 & 3: Scheme 36

6 The Code Tracing Procedures

(define F > (F '(a 1 b 2 c 3 d 4 e 5)) > (trace F) (lambda (l) (a 2 b 3 c 4 d 5 e 6) (F) (if (null? l) ( ) > (F '(1 2 3 4)) | | |() (if (number? (car l)) |(F (1 2 3 4)) | | (5) (cons (+ 1 (car l)) | (F (2 3 4)) | |(4 5) (F (cdr l))) | |(F (3 4)) | (3 4 5) (cons (car l) | | (F (4)) |(2 3 4 5) (F (cdr l))))))) | | |(F ()) (2 3 4 5)

CS 421 Lecture 2 & 3: Scheme 37 CS 421 Lecture 2 & 3: Scheme 38

Understanding cons Box Diagrams

•cons creates a new pair each time it is called! List notation Pair notation •eq? on pairs returns true if and only if the two pairs are the same pairs (a b c d) (a . (b . (c . (d . ())))

> (eq? a a) ¾ (define a (cons 3 ’())) #t > (eq? a b) ¾ (define b (cons 3 ’())) #f (a (b c) d) (a . ((b . (c . ())). (d . ())))) > (eq? ’() ’()) #t > (eq? (car a) (car b)) #t

CS 421 Lecture 2 & 3: Scheme 39 CS 421 Lecture 2 & 3: Scheme 40

Other List Operations Implementing append

{ append is syntactic sugar provided by Scheme append takes two or more lists and { Here is how it could be defined for two elements: constructs a new list with all of their > (define my-app elements: (lambda (lis1 lis2) >(append ’(a b) ’(c d)) (if (null? lis1) l2 (a b c d) (cons (car lis1) (my-app (cdr lis1) lis2))))) > (my-app '(1 2 3) '(4 5 6)) (1 2 3 4 5 6) >(list '(a b) '(c d)) { Beware when you mutate bindings and pass lists! ((a b) (c d)) lis2 is reused!

CS 421 Lecture 2 & 3: Scheme 41 CS 421 Lecture 2 & 3: Scheme 42

7 Pairs Pairs can be shared

{ Pairs are a derived data type ¾ (define c ’(1 . a)) Values: (datum . datum) Operations: cons, car, cdr, pair?, eq? ¾ (define d (cons 2 c))

¾ (define e (cons 2 c)) { Lists are internally represented as pairs (a b c d) (a . (b . (c . (d . ()))) ¾ (eq? d e) (a (b c) d) (a . ((b . (c . ())). (d . ())))) #f

{ Box Diagrams: Recall that pairs are ¾ (eq? (cadr d) (cadr e)) represented by boxes with car and cdr fields. LHS of dot is car and RHS is cdr #t

CS 421 Lecture 2 & 3: Scheme 43 CS 421 Lecture 2 & 3: Scheme 44

Vectors Higher-Order Procedures

Composition of functions. { Vectors are a derived type If g : A Æ B and f : B Æ C then f ● g : A Æ C { Provide random access instead of is defined as sequential access to elements (f ● g) (x) = f (g (x)) > (define compose >(define v1 (vector 1 (+ 1 1))) > (vector-ref v1 0) 1 (lambda (f g) >v1 (lambda (x) #2 (1 2) > (vector-ref (vector-ref v2 1) 1) (f (g x))))) 2 >(define v2 (vector v1 v1)) > (vector-length v2) > ((compose car cdr) ’(a b c d)) 2 >v2 b #2 (#0=#2 (1 2)) ¾(vector->list v2) (#0=#2(1 2) #0#)

CS 421 Lecture 2 & 3: Scheme 45 CS 421 Lecture 2 & 3: Scheme 46

Higher-order Procedure (contd.) Curried Functions

¾ ((compose list (compose cdr cdr)) Multiple argument function can be ’(a b c d)) represented by single argument ((c d)) functions. Let f : A x B Æ C >(define car-of-cdr (compose car cdr)) Define curry : (A x B) Æ (A Æ B Æ C) curry(f)(x)(y) = f(x,y) >(car-of-cdr ‘(a b c d)) b 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 ¾ (define add1 Examples: list, vector, string, +, *, ... Variable arity procedures can be defined as (lambda (f) ((curry +) 1)) (lambda formal body) (lambda (x) Formal: A single variable. Scheme binds all arguments into a list (lambda (y) ¾ (add1 4) Body: An expression (f x y))))) 5 > ((lambda x x) 1 2 3) (1 2 3) > (((curry +) 1) 2) > (define my-list (lambda x x)) 3 > (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 > (plus) { More syntactic sugar { complains if 0 arguments, "wrong number of >(let ((x 11) (y 12)) (+ x y)) { takes 1 or 2 arguments, arguments“ 33 { ignores more arguments. > (plus 1) >(define plus 1 Is equivalent to: (lambda lst (((lambda (x) (if (null? lst > (plus 2 3) (write "wrong number 5 (lambda (y) of arguments") (+ x y))) 11) 12) (if (null? (cdr lst)) > (plus 2 3 4) (car lst) 5 { More complicated with recursion in the bindings (+ (car lst) (cadr lst))))))

CS 421 Lecture 2 & 3: Scheme 51 CS 421 Lecture 2 & 3: Scheme 52

Search for zero-crossing Example: Finding Roots (Scheme code)

(define search { Finding roots of equation f(x)=0, where f (lambda (f neg-point pos-point) is continuous (let ((midpoint (average neg-point pos-point))) (if (close-enough? neg-point pos-point) { Given points f(a)<00, (search f neg-point midpoint)) ((negative? test-value) search between f(a) and f(x), otherwise (search f midpoint pos-point)) between f(x) and f(b). (else midpoint)))))))

See, Abelson and Sussman, The Structure (define close-enough? and Interpretation of Computer Programs. (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 { An Introduction to Scheme and its is defined by: Implementation f (x + dx) − f (x) http://www.federated.com/~jim/schintro-v14/schintro_toc.html Df (x) = dx { Structure and Interpretation of Computer (define derivative Programs (lambda (f dx) http://mitpress.mit.edu/sicp/full-text/book/book.html (lambda (x) (/ (– (f (+ x dx)) (f x)) { Revised5 Report on the Algorithmic dx))) Language Scheme http://www.schemers.org/Documents/Standards/R5RS/

CS 421 Lecture 2 & 3: Scheme 55 CS 421 Lecture 2 & 3: Scheme 56

10