Related material in How to Design Programs: intermezzo 3
(1) to study:
(1a) a new programming construct, local
definitions,
(1b) and a related programming concept, lexical scope;
(2) how to approach new constructs: syntax, semantics, pragmatics
Syntax (aka Grammar):
(local ((define a-name rhs-expression) ... (define another-name another-rhs-expression)) the-expression)
Syntax example:
(local ((define x 10) (define y (+ x 10))) (+ x (* 10 y)))
Semantics (aka meaning):
The evaluation of a local
expression proceeds in stages.
It begins with the evaluation of the first definition. The evaluation
proceeds just like for a normal, aka top-level, definition. Once we know
the value of the rhs-expression
, a-name
stands for this
value inside the local
expression. After all definitions
are evaluated, the evaluator reduces the-expression
to a
value. This last value is the result of the local
expression.
Semantics example:
(local ((define x 10) (define y (+ x 10))) (+ x (* 10 y)))
First, 10
is a value, so x
stands for
10
. Second, (+ x 10)
accordingly evaluates to
20
, and y
represents 20
. Finally, (+ x
(* 10 y))
evaluates to 210
because x
is 10
and
y
is 20
inside this local
expression. Hence, the
result of the local
expression is 210
.
On to pragmatics.
;;Posn → Number
;; determine the distance ofp
to the origin: √((px)2 + (py)2) ;; example:(distance0 (make-posn 3 4))
is5
(define (distance0 p) (sqrt (+ (sqr (posn-x p)) (sqr (posn-y p))))) ;; tests: (= (distance0 (make-posn 3 4)) 5) (= (distance0 (make-posn 12 5)) 13)
Here is a “slower” version:
;;Posn → Number
;; determine the distance ofp
to the origin: √((px)2 + (py)2) ;; example:(distance0 (make-posn 3 4))
is5
(define (distance0 p) (local ((define x (posn-x p)) (define y (posn-y p)) (define sqrx (sqr x)) (define sqry (sqr y)) (define sum (+ sqrx sqry))) (sqrt sum))) ;; tests: (= (distance0 (make-posn 3 4)) 5) (= (distance0 (make-posn 12 5)) 13)