147pm
147pm

Reputation: 2239

Why reassign functions inside Scheme let?

This is code from Simply Scheme (code here) which the student is supposed to load and use as we follow along with the exercises. (Note: I'm an individual doing this for myself only.)

(define first
  (let ((pair? pair?)
    (char->word char->word)
    (string-ref string-ref)`
    (word->string word->string)
    (car car)
    (empty? empty?)
    (whoops whoops)
    (word? word?))
    (define (word-first wd)
      (char->word (string-ref (word->string wd) 0)))
    (lambda (x)
      (cond ((pair? x) (car x))
        ((empty? x) (whoops "Invalid argument to FIRST: " x))
        ((word? x) (word-first x))
        (else (whoops "Invalid argument to FIRST: " x))))))

I'm well enough along to understand the general use of let and lambda in this function, but what I don't understand is why in the let form each supporting function (some homemade, some batteries-included Scheme) are being repeated, e.g., (pair? pair?) and (car car). Why are these being quasi-reassigned inside this let?

Upvotes: 1

Views: 60

Answers (1)

C. K. Young
C. K. Young

Reputation: 223183

The code is designed for use as "library code" in a variety of Scheme implementations, including ones where built-in bindings could be redefined. The lets ensure that the original bindings will be used in the library functions, even if the user redefines the top-level bindings later on.

For non-library code that you write, you will generally not have to worry about that. Also, if you're using a Scheme implementation with a module system that enforces immutable module bindings (such as Racket), that won't be a concern either.

Upvotes: 5

Related Questions