1 Programming Languages (CS 550) Lecture 7 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts used in EMF. Read.

Slides:



Advertisements
Similar presentations
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Advertisements

1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Scheme in Scheme?!? …the metacircular evaluator….
1 The metacircular evaluator Names Extend the calculator to store intermediate results as named values (define x (+ 4 5)) store result as x (+ x.
1 Programming Languages (CS 550) Operational Semantics of Scheme using Substitution and the Lambda Calculus Jeremy R. Johnson TexPoint fonts used in EMF.
Metacircular Evaluation SICP Chapter 4 Mark Boady.
מבוא מורחב למדעי המחשב תרגול 13 Lazy Evaluation. Lazy Evaluation Implementation Two types of values – Delayed Values – Actual Values Introduce two functions.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
1 The Metacircular Evaluator Chapter 4 Section 4.1 We will not cover every little detail in the lectures, so you MUST read Section 4.1 in full.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 11. Metacircular Evaluator 4.1, pages definitions file on web 2.
(define applicative-eval (lambda (exp) (cond ((atomic? exp) (eval-atomic exp)) ((special-form? exp) (eval-special-form exp)) ((list-form? exp) (eval-list.
מבוא מורחב - שיעור 15 1 Lecture 15 Streams. מבוא מורחב - שיעור 15 2 Streams: Motivation (define (sum-primes a b) (define (iter count accum) (cond ((>
1 Lecture 18 Continue Evaluator. 2 z9 true#t + twice Representing procedures (eval '(define twice (lambda (x) (+ x x))) GE) symbol primitive scheme procedure.
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 21. Overview 1. Dynamic Binding 2. Lazy Evaluation 3. More MC-Eval 2.
Lexical vs. Dynamic Scope …where do I point to?. Intro… Remember in Scheme whenever we call a procedure we pop a frame and point it to where the procedure.
SICP Variations on a Scheme Scheme Evaluator – A Grand Tour Techniques for language design: Interpretation: eval/apply Semantics vs. syntax Syntactic.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Scheme More MCE examples. Q1 new special form which defines global variables (static ) search the global environment – Variable exists: does nothing,
SICP Variations on a Scheme (2) Beyond Scheme – designing language variants: Lazy evaluation Complete conversion – normal order evaluator Upward.
The environment model evaluator and compiler 1 The env model evaluator Motivation In one word: Efficiency Saves repeated renaming and substitution: Using.
1 Saves repeated renaming and substitution: explicit substitution is replaced by variable bindings using new data structures (frame, environment). Can.
Closures and Streams More on Evaluations CS784(pm)1.
1 Lecture OO, the notion of inheritance 3 Stacks in OO style (define (make-stack) (let ((top-ptr '())) (define (empty?) (null? top-ptr)) (define.
1 Continue Evaluator. 2 z9 true#t + twice Representing procedures (eval '(define twice (lambda (x) (+ x x))) GE) symbol primitive scheme procedure + symbol.
1 Programming Languages (CS 550) Lecture 5 Summary Object Oriented Programming and Implementation* Jeremy R. Johnson *Lecture based on notes from SICP.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is aa good way to learn more about programming languages  Interpreters are.
1 The metacircular evaluator (Cont.) Defining new procedures (define (lambda? e) (tag-check e 'lambda)) (define (eval exp env) (cond ((number? exp)
CS220 Programming Principles 프로그래밍의 이해 2002 가을학기 Class 15: Meta-Circular Evaluator 한 태숙.
SICP Interpretation Parts of an interpreter Arithmetic calculator Names Conditionals and if Storing procedures in the environment Environment as.
1 Subt. model interpreter: Structure of the interpreter ASP Derived expressions Core Test Data structures Utils A racket lib Proc / Primitive-Proc. Global.
SICP Explicit-control evaluator Big ideas: how to connect evaluator to machine instructions how to achieve tail recursion Obfuscation: tightly.
© Kenneth C. Louden, Chapter 11 - Functional Programming, Part III: Theory Programming Languages: Principles and Practice, 2nd Ed. Kenneth C. Louden.
The environment-based operational semantics Chapter
1 Lecture 20 Lazy Evaluation Continued (4.2.1, 4.2.2) MC-eval examples from exams (Time permitting)
1 Read-Eval-Print Loop (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (eval input the-global-env))) (announce-output.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
1 Subt. model interpreter: Introduction Abstract Syntax Parser Abstract Syntax Parser Derived Expressions Core Test Data Structures Utils (a racket lib)
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
1 Env. Model Implementation & Analyzer Practice Session #10 Env. Model Implementation & Analyzer Practice Session #10.
1 Lecture 19 Dynamic Scoping Lazy Evaluation (4.2.1, 4.2.2)
1/ SICP Variations on a Scheme Scheme Evaluator – A Grand Tour Making the environment model concrete Defining eval defines the language –Provides.
1 Programming Languages (CS 550) Lecture 2 Summary Mini Language Interpreter Jeremy R. Johnson.
1 Lecture 19 Review last lecture on evaluator, Dynamic Scoping Lazy Evaluation (4.2.1, 4.2.2)
CSE 425: Functional Programming I Programs as Functions Some programs act like mathematical functions –Associate a set of input values from the function’s.
C H A P T E R E I G H T Functional Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane.
SICP Interpretation part 2 Store operators in the environment Environment as explicit parameter Defining new procedures.
Operational Semantics of Scheme
CS 550 Programming Languages Jeremy Johnson
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
6.001 SICP Variations on a Scheme
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Env. Model Implementation
Nondeterministic Evaluation
Mini Language Interpreter Programming Languages (CS 550)
The Metacircular Evaluator
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
The Metacircular Evaluator (Continued)
Lecture 26: The Metacircular Evaluator Eval Apply
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
6.001 SICP Variations on a Scheme
6.001 SICP Interpretation Parts of an interpreter
topics interpreters meta-linguistic abstraction eval and apply
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

1 Programming Languages (CS 550) Lecture 7 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: AAA A A A

2 Starting Point Informal Scheme Semantics  To evaluate (E1 E2... En), recursively evaluate E1, E2,...,En - E1 should evaluate to a function - and then apply the function value of E1 to the arguments given by the values of E2,...,En.  In the base case, there are self evaluating expressions (e.g. numbers and symbols). In addition, various special forms such as quote and if must be handled separately.

3 Theme  This lecture continues our exploration of the semantics of scheme programs. Previously we informally discussed the substitution model, environments, and provided an interpreter for scheme that operationally defined the semantics of scheme programs.  In this lecture we will more formally study the substitution model using the lambda calculus. We will also look at alternative (lazy) semantics for scheme and an implementation of streams.

4 Lambda Calculus  The semantics of a pure functional programming language can be mathematically described by a substitution process that mimics our understanding of function application - i.e., substitute all occurrences of the formal parameters of a function in the function body by the arguments in the function call.  In order to formally study function definition and application and computability, logicians (Alonzo Church, Stephen Cole Kleene, and others) in the 1930s developed a formal notation called the lambda calculus and rules defining an equivalence relation on lambda expressions that encodes function definition and application.  They showed the universality of the lambda calculus, the uniqueness of normal forms, and the undecidablity of the equivalence of lambda expressions.

5 Outline  Review substitution model of computation  Review shortcomings of substitution model  Review streams and delayed evaluation  Adding support for streams  Interpreter with lazy semantics  Lambda calculus  Free and bound variables  alpha and beta reduction  Universality of lambda calculus

6 Substitution Model of Computation  function application corresponds to substituting the argument expressions into the formal parameters of the function body  Order of evaluation  Applicative vs. normal order  lambda calculus  Church-Rosser

7 Substitution Example  (define (square x) (* x x))  (define (sum-of-squares x y) (+ (square x) (square y)))  (define (f a) (sum-of-squares (+ a 1) (* a 2))) [applicative order]  (f 5)  (sum-of-squares (+ 5 1) (* 5 2))  (+ (square 6) (square 10))  (+ (* 6 6) (* 10 10))  ( )  136 [normal order]  (f 5)  (sum-of-squares (+ 5 1) (* 5 2))  (+ (square (+ 5 1)) (square (* 5 2)) )  (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2)))  (+ (* 6 6) (* 10 10))  ( )

8 Order Matters (define (p) (p)) (define (test x y) (if (= x 0) 0 y)) (test 0 (p))

9 Environments  When assignment is introduced the substitution model falls apart and a different model, more complicated model, must be used.  Environments used to store variables and bindings.  Values can change  assignment supported  List of frames to support nested scope

10 Cost of Assignment (define (make-simplified-withdraw balance) (lambda (amount) (set! balance (- balance amount)) balance)) (define W (make-simplified-withdraw 25)) (W 10) 15 (W 10) 5 (define (make-decrementer balance) (lambda (amount) (- balance amount))) (define D (make-decrementer 25)) (D 10) 15 (D 10) 15

11 Substitution Model Fails (make-decrementer 25) 20)  ((lambda (amount) (- 25 amount)) 20)  ( )  5 ((make-simplified-withdraw 25) 20)  ((lambda (amount) (set! balance (- 25 amount)) 25) 20)  (set! balance ( )) 25

12 Environment Model Solves Problem (define W1 (make-withdraw 100)) (W1 50) (define W2 (make-withdraw 100)) Global Env Balance = 50Balance = 100 E1 E2 Parameters body W1W2 Make-withdraw

13 Streams  Sequence of elements  (cons-stream x y)  (stream-car s)  (stream-cdr s)  (stream-null? s)  the-empty-stream

14 Streams are Not Lists  Consider the following example (car (cdr (filter prime? (enumerate-interval ))))  This would be extremely inefficient if implemented with lists  Do not build the entire stream of elements  Get the next element from the stream when needed  Necessary for potentially infinite streams

15 Delayed Binding (cons-stream )  (cons (delay )) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) (delay )  (lambda () ) (define (force delayed-object) (delayed-object))

16 Scheme Interpreter 1.To evaluate a combination (a compound expression other than a special form), evaluate the subexpressions and then apply the value of the operator subexpression to the values of the operand subexpressions. 2.To apply a compound procedure to a set of arguments, evaluate the body of the procedure in a new environment. To construct this environment, extend the environment part of the procedure object by a frame in which the formal parameters of the procedure are bound to the arguments to which the procedure is applied.

17 Scheme Interpreter: eval (define (eval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (eval (cond->if exp) env)) ((application? exp) (apply (eval (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type -- EVAL" exp))))

18 Scheme Interpreter: apply (define (apply procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure))))

19 Stream Practice Exercises  Complete the trace of (stream-car (stream-cdr (stream-filter prime? (stream-enumerate-interval ))))  Modify the scheme interpreter from SICP to support force, delay and streams. You should implement everything needed to execute the above computation.

20 Scheme Interpreter with Streams ; added to eval ((delay? exp) (eval-delay exp env)) ((cons-stream? exp) (eval-cons-stream exp env)) ; new functions (define (delay? exp) (tagged-list? exp 'delay)) (define (eval-delay exp env) (make-procedure '() (cdr exp) env)) (define (eval-cons-stream exp env) (eval (list 'cons (cons-stream-op1 exp) (list 'delay (cons-stream-op2 exp))) env))

21 Scheme Interpreter with Streams ;*** The following need to be defined in the metacircular evaluator to ;*** complete the implementation of streams. (define (force delayed-object) (delayed-object) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) (define (stream-null? stream) (null? stream))

22 Lazy Evaluation  Language with normal order semantics. Compound procedures are non-strict, while primitive procedures remain strict.  Procedure strict if arg evaluated before entering  Procedure non-strict if proc not evaluated before entering  Delaying evaluation until last possible moment is called lazy evaluation.  Delay evaluation of arguments by converting them to thunks.  A thunk is forced only when its value is needed.  Memoize thunks to avoid repeated evaluation.

23 Examples of Lazy Evaluation (define (try a b) (if (= a 0) 1 b)) (try 0 (/ 1 0)) (define (unless condition usual-value exceptional-value) (if condition exceptional-value usual-value)) (unless (= b 0) (/ a b) (begin (display "exception: returning 0") 0))

24 Lazy Scheme Interpreter: eval ((application? exp) (apply (actual-value (operator exp) env) (operands exp) env)) (define (actual-value exp env) (force-it (eval exp env))) (define (eval-if exp env) (if (true? (actual-value (if-predicate exp) env)) (eval (if-consequent exp) env) (eval (if-alternative exp) env)))

25 Lazy Scheme Interpreter: apply (define (apply procedure arguments env) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env))) ; changed ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) ; changed (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure))))

26 Lazy Scheme Interpreter: apply (define (list-of-arg-values exps env) (if (no-operands? exps) '() (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exps) env)))) (define (list-of-delayed-args exps env) (if (no-operands? exps) '() (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env))))

27 Representing Thunks (define (force-it obj) (if (thunk? obj) (actual-value (thunk-exp obj) (thunk-env obj)) obj)) (define (delay-it exp env) (list 'thunk exp env)) (define (thunk? obj) (tagged-list? obj 'thunk))

28 Lazy Evaluation in Action (define input-prompt ";;; L-Eval input:") (define output-prompt ";;; L-Eval value:") (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (actual-value input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (define the-global-environment (setup- environment)) (driver-loop) ;;; L-Eval input: (define (try a b) (if (= a 0) 1 b)) ;;; L-Eval value: ok ;;; L-Eval input: (try 0 (/ 1 0)) ;;; L-Eval value: 1

29 Memoization (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) (fib 5)

30 Memoization (define (memoize f) (let ((table (make-1d-table))) (lambda (x) (let ((previously-computed-result (1d-table/get table x #f))) (or previously-computed-result (let ((result (f x))) (1d-table/put! table x result) result)))))) (define memo-fib (memoize (lambda (n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (memo-fib (- n 1)) (memo-fib (- n 2))))))))

31 Memoized Thunks (define (evaluated-thunk? obj) (tagged-list? obj 'evaluated-thunk)) (define (thunk-value evaluated-thunk) (cadr evaluated-thunk)) (define (force-it obj) (cond ((thunk? obj) (let ((result (actual-value (thunk-exp obj) (thunk-env obj)))) (set-car! obj 'evaluated-thunk) (set-car! (cdr obj) result) ; replace exp with its value (set-cdr! (cdr obj) '()) ; forget unneeded env result)) ((evaluated-thunk? obj) (thunk-value obj)) (else obj)))

32 Streams for Free  Previous implementation of streams required new special forms delay and cons-stream and the reimplementation of list functions for streams.  In the lazy evaluator lists and streams are identical!  Just need to make sure that cons is non-strict  Reimplement cons primitive  Or implement cons, car, and cdr as functions (see lambda calculus)

33 Lambda Calculus Expressions 1. → variable 2.application: → ( ) 3.abstraction: → (lambda variable. )  Use currying to allow more than one parameter

34 Free and Bound Variables  The parameter of an abstraction is bound in the lambda body  (lambda (x) E)  Variables not bound by a lambda are free

35 Lambda Calculus Reductions 1.alpha conversion: (lambda x.E) is equivalent to (lambda y,E[y/x]) provided y does not appear free in E and y is not bound by a lambda when substituted for x in E. 2.beta reduction: ((lambda x.E) F) is equivalent to E[F/x], where F is substituted for all free occurrences of the variable x in E, provided all free variables in F remain free when substituted for x in E.

36 Universality of Lambda Calculus 1.Church numerals and arithmetic using lambda calculus 2.boolean logic, predicates, and conditional statements using lambda calculus 3.Data structures (lists, cons, car, cdr) using lambda calculus 4. Recursion using lambda calculus

37 Y Combinator (define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) 1.(define Y (lambda (g) ((lambda (x) (g (x x))) (lambda (x) (g (x x)))))) 2.(g (Y g)) = (Y g) [fixed point] 3.(define g (lambda (n f) (if (= n 0) 1 (* n (f (- n 1)))))) 4.(g (Y g) n)

38 Lambda Calculus Practice Exc. 1 Implement a scheme function (FV exp), which returns a list of the free variables in the scheme expression exp. The scheme expression will not have let, letrec, or let* statements - the only bindings come from labda expressions.

39 Lambda Calculus Practice Exc. 2 Show that the and, or, and not functions using the lambda calculus in lecture 2b are correct by showing that the correct result is obtained for all combinations of the inputs.

40 Lambda Calculus Practice Exc. 3 Using beta-reduction show that (succ two) is three, where two and three are the Church encodings the numbers 2 and 3 (see the scheme code for Church numbers in lecture 2b. Use induction to prove that ((cn add1) 0) = the number n, where cn is the Church encoding of n. You may assume that add1 correctly adds 1 to its input.

41 Lambda Calculus Practice Exc. 4 Trace through the expansion (use beta reduction) of (g (Y g) 3) using the functions g and Y from the discussion on the Y combinator. Try implementing g and Y and computing (g (Y g) 3) in scheme. What happens and why? Try this again using the normal order scheme interpreter in Section of SICP.

42 Lambda Calculus Practice Exc. 5 Implement a scheme function that performs a beta reduction. You must also have a predicate which checks to see if the beta reduction is valid (i.e. the substitution does not cause problems with name collisions)