#lang racket ;; CSE 413 19wi ;; Lecture 7 sample code ;; Environments and closures ;; Hal Perkins (define nums '(1 2 3 4 5)) (define rnums '(17 3 -2 42 15 3 12)) (define alist '(a (b c) d e)) (define x 17) (define y 42) (define (incr n) (+ 1 n)) (define (dbl n) (* 2 n)) ;; expressions & global variables (+ x 1) ;; let and let* expressions ;; same environments, difference is which environment is ;; searched first in initialization (let ([x 2] [y (+ 1 x)]) (+ x y)) (let* ([x 2] [y (+ 1 x)]) (+ x y)) ;; A function is a closure ;; (lambda ...) evaluates to a closure ;; whose environment env references the ;; environment where lambda was evaluated ;; function call: ;; 1) Create new environment whose parent is ;; env from closure ;; 2) Bind parameter names to values in new environment ;; 3) Evaluate function in this environment ;; simple function closures (define plus (lambda (x y) (+ x y))) ;; function closure with global names (define plusx (lambda (n) (+ x n))) ;; (plusx 2)