number ;; ...">

Using Local in Racket / Scheme

In exercise 18.1.12 from htdp, I rewrote the maxi function with "local".

;; maxi : non-empty-lon  ->  number
;; to determine the largest number on alon
(define (maxi alon)
  (cond
    [(empty? (rest alon)) (first alon)]
    [else (local ((define m (maxi (rest alon))))
            (cond
              [(> (first alon) m) (first alon)]
              [(> m (first (rest alon))) m]
              [else (first (rest alon))]))]))

I'm not sure why I will do this in "real life", as it seems that the book version is shorter, clearer, and probably faster.

(define (maxi alon)
  (cond
    [(empty? (rest alon)) (first alon)]
    [else (cond
        [(> (first alon) (maxi (rest alon))) (first alon)]
        [else (maxi (rest alon))])]))

Was this a purely pedagogical exercise? Can an experienced developer comment on the code above? Thank.

+5
source share
3 answers

Personally, I think this is a bad example of importance local, and I do not believe that you fully understood the importance of the question, so I will do this through a concept that you should notice, then go through your example and finally give you a better example.

CONCEPT

-, ( many) , .

, m, . , m , . , ?

m , , m. , , m, (maxi (rest alon))

(maxi (rest alon)) , (rest alon)

, m find-max

:

;; maxi : non-empty-lon  ->  number
;; to determine the largest number on alon
(define (maxi alon)
  (cond
    [(empty? (rest alon)) (first alon)]
    [else (local ((define find-max (maxi (rest alon))))
            (cond
              [(> (first alon) find-max) (first alon)]
              [(> find-max (first (rest alon))) find-max]
              [else (first (rest alon))]))]))

m find-max ! , .

, , . :

;;where x1,y1 belong to point 1 and x2,y2 belong to point 2
(define (find-slope x1 y1 x2 y2)
  (sqrt (+ (sqr (- x2 x1))) (sqr (- y2 y1))))

local:

(define (find-slope x1 y1 x2 y2)
  (local
    [(define delta-x (- x2 x1))
     (define delta-y (- y2 y1))]
    (sqrt (+ (sqr delta-x)) (sqr delta-y))))

, delta , ; x y. , , , , , , . , , , .

, , , ( , , Racket ), .

,

+3

local Racket ( ).

:

(define (maxi alon)
  (cond
    [(empty? (rest alon)) (first alon)]
    [else (define m (maxi (rest alon)))        ; here is an internal define
          (cond
            [(> (first alon) m) (first alon)]
            [(> m (first (rest alon))) m]
            [else (first (rest alon))])]))
+3

Using the local path here is faster because it evaluates only (maxi (rest alon))once per recursion, whereas with the second version it evaluates twice (maxi (rest alon))each time it falls into the last case.

Local saves the result, so you do not do the same job twice.

0
source

All Articles