Search code examples
schemesicp

How do I get the functions put and get in SICP, Scheme, Exercise 2.78 and on


I am trying to do exercise 2.78 in SICP, but the functions put and get are unknown. I have tried multiple languages, like pretty big, racket, r5rs, mit-scheme, mzscheme, etc. I even downloaded the SICP support (http://www.neilvandyke.org/sicp-plt/), to no avail. How can I get these functions to work?


Solution

  • Yes, I found SICP a little annoying sometimes because of stuff like this. Functions that are assumed to exist but don't actually exist make it harder to try to the examples. I wrote my own (get) and (put) like so (this was in GNU guile):

    (define global-array '())
    
    (define (make-entry k v) (list k v))
    (define (key entry) (car entry))
    (define (value entry) (cadr entry))
    
    (define (put op type item)
      (define (put-helper k array)
        (cond ((null? array) (list(make-entry k item)))
              ((equal? (key (car array)) k) array)
              (else (cons (car array) (put-helper k (cdr array))))))
      (set! global-array (put-helper (list op type) global-array)))
    
    (define (get op type)
      (define (get-helper k array)
        (cond ((null? array) #f)
              ((equal? (key (car array)) k) (value (car array)))
              (else (get-helper k (cdr array)))))
      (get-helper (list op type) global-array))
    

    Probably a naive implementation from the perspective of later in the book, but fairly simple and worked fine.