; local binding ; binding in Scheme means assigning values to variables ; local binding will be assigning values to variables for a limited, ; or "local" scope ; examples of binding ; (define dozen 12) this globally binds the value 12 to the variable dozen ; we say globally because all procedures in the Scheme session know the value ;of dozen ; (define square ; (lambda (x) ; (* x x))) ; in this example x will be bound to the input value for the scope ; of the the expression (* x x) ; specifically, (square 5) will cause x to be bound to the value 5 ; using LET, we can bind values to variables for an even smaller scope ; syntax of LET ; (let ((VARIABLE1 VALUE1) ; (VARIABLE2 VALUE2) ; ... ; (VARIABLEn VALUEn)) ; EXPRESSION) ; this executes the expression with the values bound to variables ; notice that the parenthesis structure is like cond ; examples (let ((a 1) (b 2) (c 3)) (* a b c)) ; note that in a let statement, you cannot refer to variables that you have ; just defined, in the values of others, so this will cause an error ;(let ; ((a 1) ; (b (+ a 1)) ; (c (+ b 1))) ; (* a b c)) ; this will work fine because LET* allows all bound variables to see the others (let* ((a 1) (b (+ a 1)) (c (+ b 1))) (* a b c)) ; there are actually some very compelling uses for LET ; suppose we write max-of-list, but without the MAX procedure ;(define max-of-list ; (lambda (ls) ; (if (null? (cdr ls)) ; (car ls) ; (if (> (car ls) (max-of-list (cdr ls))) ; (car ls) ; (max-of-list (cdr ls)))))) ; we will use this procedure from the recursion with integers lab to ; generate a long list (define count-from (lambda (lower upper) (if (= lower upper) (list upper) (cons lower (count-from (+ lower 1) upper))))) ; problem, (max-of-list '(1 ... 100)) takes a long long time..... ; root of the problem, each call to max-of-list, places 2 more calls ; fix, use LET (define max-of-list (lambda (ls) (if (null? (cdr ls)) (car ls) ; this LET statement binds the variable MAX-OF-CDR to the value ; (max-of-list (cdr ls)) (let ((max-of-cdr (max-of-list (cdr ls)))) (if (> (car ls) max-of-cdr) (car ls) max-of-cdr))))) ; now (max-of-list (count-from 1 100)) runs quickly!