Environment Model Examples
This tutorial, presented by Prof. Tony White, delves into the intricate world of environment models, showcasing a myriad of examples from functional programming concepts. Through a series of practical examples, such as function definitions, lambda expressions, and iterative processes, you will explore how these environments handle variable scoping, operations, and computations. The content is designed to enrich your understanding of programming languages and their foundational principles, particularly in a functional context.
Environment Model Examples
E N D
Presentation Transcript
Environment Model Examples Prof. Tony White April 2010 Ref: http://www.cs.caltech.edu/courses/cs1/resources/environment-model-tutorial/environments.html
Example 1 1. (define (foox) (+ x 1)) 2. (foo 2) foo’ Π=1 Π=3
Example 2 (let ((x 1) (y 2)) (+ xy)) let’ Π=3 Π=4
Example 3 1. (lambda (xy) (+ xy)) 1 2) lambda’ Π=1 Π=2
(define (sqrtff) (lambda (x) (sqrt (fx)))) (define (inc n) (+ n 1)) (define f1 (sqrtf inc)) (f1 3) Example 4-a Π=4
(define (sqrtff) (lambda (x) (sqrt (fx)))) (define (inc n) (+ n 1)) (define f1 (sqrtf inc)) (f1 3) Example 4-b sqrtf’ Π=5
(define (sqrtff) (lambda (x) (sqrt (fx)))) (define (inc n) (+ n 1)) (define f1 (sqrtf inc)) (f1 3) Example 4-c sqrtf’ f1’ Π=2 Π=6
(define (sqrtff) (lambda (x) (sqrt (fx)))) (define (inc n) (+ n 1)) (define f1 (sqrtf inc)) (f1 3) Example 4-d sqrtf’ f’ f1’ Π=3 Π=2 Π=6
(define bar (let ((x 1) (y 2)) (lambda (z) (+ xyz)))) (bar 3) Example 5-a let’ Π=5
(define bar (let ((x 1) (y 2)) (lambda (z) (+ xyz)))) (bar 3) Example 5-b let’ bar’ Π=4 Π=6
Example 6: Code (define (fooz) (let ((xz)) (let ((y (+ xz))) (lambda (sym) (cond ((eq? sym 'x) x) ((eq? sym 'y) y) ((eq? sym 'bump-x) (set! x (+ xz))) ((eq? sym 'bump-y) (set! y (+ yz))) ((eq? sym 'reset-x) (set! x 0)) ((eq? sym 'reset-y) (set! y 0))))))) (define f (foo 10)) (f 'x) (f 'y) (f 'bump-x) ; Rest of code not shown
Example 6-a foo’ Π=12
Example 6-b foo’ Π=5 Π=13
Example 6-c foo’ Π=7 Π=15
Example 6-d • Rest of code associated with example 6 left as an exercise to the reader. It really is a set of variations on 6-b and 6-c.
Example 7: Code (define (new-sqrtx) (define (good-enough? guess) (< (abs (- (square guess) x)) 0.000001)) (define (average xy) (/ (+ xy) 2)) (define (improve guess) (average guess (/ x guess))) (define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess)))) (sqrt-iter 1.0)) (new-sqrt 2.0)
Example 7-a Π=13
Example 7-b new-sqrt’ Π=12 Π=14
Example 7-c new-sqrt’ sqrt-iter’ Π=12 Π=14 Π=9
(define (foox) (let ((y (lambda (w) (+ xw))) (z (lambda (w) (* xw)))) (y (zx)))) (foo 10) Example 8-a Π=5
(define (foox) (let ((y (lambda (w) (+ xw))) (z (lambda (w) (* xw)))) (y (zx)))) (foo 10) Example 8-b foo’ Π=2 Π=6
(define (foox) (let ((y (lambda (w) (+ xw))) (z (lambda (w) (* xw)))) (y (zx)))) (foo 10) Example 8-c foo’ let’ Π=6 Π=4 Π=2