![]() |
![]() |
|
home—info—lectures—exams—archive
We have already seen that Scheme has a let statement, which can be implemented in terms of a function-call:
(let {[a 2] [b 4]} (+ 3 a b)) = ((lambda (a b) (+ 3 a b)) 2 4) |
(define a 1) (let {[a 2] [b (sqr a)]} (+ 3 a b)) |
Scheme does happen to provide let*. let* can be implemented by expanding it into nested lets.1 Here's an example:
(define a 1) (let* {[a 2] [b (+ sqr a)]} (+ 3 a b)) = ; Rewrite as nested lets: (let {[a 2]} (let {[b (sqr a)]} (+ 3 a b))) = ; Which, following the already-known rules, becomes: ((lambda (a) (let {[b (sqr a)]} (+ 3 a b))) 2) = ; Note how there's no confusion about using the global a=1. (let {[b (sqr 2)]} (+ 3 2 b)) = (let {[b 4]} (+ 3 2 b)) = ; Now, follow regular ol' rules for evaluation a function-application: ((lambda (b) (+ 3 2 b)) 4) = (+ 3 2 4) = 9 |
Finally, what about a version where the scope includes the current let-branch? For variables, this is never desirable ('variable used before initialized'), but it is necessary for recursive functions:
(define (insert-sort lon) (letrec {[insert (lambda (n nums) (cond [(empty? nums) (list n)] [(cons? nums) (if (< n (first nums)) (cons n nums) (cons (first nums) (insert n (rest nums))))]))]} (foldl insert empty lon))) ; Another example, using mutual recursion: (letrec {[a 2] [even? (lambda (n) (or (zero? n) (odd? (sub1 n))))] [odd? (lambda (n) (not (even? n)))]} (even? a)) |
Let's ask these same questions in Java:
class Foo { static int a = 1; static int lala() { int a = 2; int b = a*a; return 3+a+b; } } |
class Foo { static int a = 1; static int lala() { int b = a*a; int a = 2; return 3+a+b; } } |
class Foo { static int a = 1; static int lala( int a ) { int b = a*a; int a = a; return 3+a+b; } } |
Two possible approaches:
1 (Therefore, let* isn't really a primitive scoping mechanism; it's just convenient syntactic sugar. In the same way that let itself can be thought of as syntactic sugar for passing to a parameter.) ↩
home—info—lectures—exams—archive
©2008, Ian Barland, Radford University Last modified 2008.Oct.29 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |