user1897830
user1897830

Reputation: 443

Racket recursive variable?

Fig. 65 in "How to Design Programs" is as follows:

; Nelon -> Number
; determines the smallest number on l
(define (inf l)
  (cond
    [(empty? (rest l)) (first l)]
    [else
     (local ((define smallest-in-rest (inf (rest l))))
       (cond
         [(< (first l) smallest-in-rest) (first l)]
         [else smallest-in-rest]))]))

Can somebody explain how variable smallest-in-rest works. I get recursion in a function but a variable has me confused

Upvotes: 0

Views: 126

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

It's just a shorthand (longhand ;-)) for the following:

(let ((smallest-in-rest (inf (rest l))))
  (cond
    [(< (first l) smallest-in-rest) (first l)]
    [else smallest-in-rest]))

The let should make it clear that we're just storing the result of the (inf (rest l)) so that it only has to be written once in the code, rather than once for each branch of the cond.

Upvotes: 1

Related Questions