연습문제 3.25 다차원 테이블 조작 학술

아 어렵다 (한숨)
별거 아닌걸로 왜 이리 삽질을..

(define (make-table)
  (let ((local-table (list '*table*)))
    (define (assoc key records)
      (cond ((null? records) false)
            ((equal? key (caar records)) (car records))
            (else (assoc key (cdr records)))))
    
    (define (lookup keys)
      (lookup-table keys local-table))
    
    (define (lookup-table keys table)
      (if table
          (if (null? keys)
              (if table  ;; record
                  (cdr table)
                  false)
              (lookup-table (cdr keys) (assoc (car keys) (cdr table))))
          false))

    (define (insert! keys value)
      (create-subtables keys local-table)
      (insert-record keys value local-table)
      'ok)
 
    (define (insert-record keys value table)
      (let ((len (length keys))
            (key (car keys))
            (subtable (assoc (car keys) (cdr table))))
        (if (= len 1)
            (let ((record (assoc (car keys) (cdr table))))
              (if record
                  (set-cdr! record value)
                  (set-cdr! table
                            (cons (cons key value)
                                  (cdr table)))))
            (insert-record (cdr keys) value subtable))))
            
    (define (create-subtables keys table)
      (let ((len (length keys)))
        (if (<= len 1)
            table
            (let ((subtable (assoc (car keys) (cdr table))))
              (if subtable
                  (create-subtables (cdr keys) subtable)
                  (begin
                    (set-cdr! table
                              (cons (cons (car keys) '())
                                    (cdr table)))
                    (create-subtables (cdr keys) (assoc (car keys) (cdr table)))))))))
    
    (define (dispatch m)
      (cond ((eq? m 'lookup) lookup)
            ((eq? m 'insert!) insert!)
            ((eq? m 'get) local-table)
            (else (error "Unknown" m ))))
    dispatch))

(define t (make-table))
((t 'insert!) '(a b c d1 e1) 1)
((t 'insert!) '(a b c d2) 'qoo)
((t 'insert!) '(a b c d1 e2) 2)
((t 'insert!) '(a b c d1 e3) 3)
(t 'get)
((t 'lookup) '(a b c d1 e1))
((t 'lookup) '(a b c d2))
((t 'lookup) '(a b c d1 e2))
((t 'lookup) '(a b c d1 e3))

결과:
ok
ok
ok
ok
(*table* (a (b (c (d2 . qoo) (d1 (e3 . 3) (e2 . 2) (e1 . 1))))))
1
qoo
2
3


트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://xeraph.com/tb/4147644 [도움말]

핑백

  • Xeraph beyond the Great Firewall : 2008년 회고록 (작성 중) 2008-12-18 00:05:04 #

    ... 진행했었는데, 이건 예전 글을 참고하세요. 중도에 그만둬서 안타깝지만 그래도 상당히 빡세게 진도 나갔습니다. SICP의 중턱에서연습문제 3.25 다차원 테이블 조작SICP 연습문제 3.27SICP 연습문제 3.19 토끼와 거북이SICP 7차 모임 문제 할당SICP 6차 문제 할당SIC ... more

덧글

댓글 입력 영역