読者です 読者をやめる 読者になる 読者になる

(wat-aro)

無職から有職者にランクアップしました

SICP 問題 3.25

;; keyではなくkey-listを'(x y z)という形で渡す
;; key-listのcdrがnullになるまで再帰すればkeyの数がいくつでも対応できる
(define (make-table)
  (let ((local-table (list '*local-table*)))
    (define (lookup key-list)
      (let loop ((key-list key-list)
                 (table local-table))
        (if (null? key-list)
            false
            (let ((record (assoc (car key-list) (cdr table))))
              (and record
                   (if (null? (cdr key-list))
                       record
                       (loop (cdr key-list) recordf)))))))
    (define (insert! key-list value)
      (let loop ((key-list key-list)
                 (table local-table))
        (if (null? key-list)
            false
            (let ((record (assoc (car key-list) (cdr table))))
              (if record
                  (if (null? (cdr key-list))
                      (set-cdr! record value)
                      (loop (cdr key-list)
                            record))
                  (set-cdr! table
                            (cons (cons (car key-list) value)
                                  (cdr table)))))))
      'ok)
    (define (dispatch m)
      (cond ((eq? m 'lookup-proc) lookup)
            ((eq? m 'insert-proc!) insert!)
            (else (error "Unknown operation -- TABLE" m)))))
  dispatch)