learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-6.scm (20090B)


      1 (define-library (sicp solutions chapter-4 exercise-6)
      2   (export
      3    eval
      4    main
      5 
      6    run-internal-tests
      7 
      8    make-environment
      9    setup-environment
     10    extend-environment
     11    )
     12   (import
     13    (rename (scheme base) (apply scheme:base:apply))
     14    (scheme cxr)
     15    (scheme read)
     16    (scheme write)
     17 
     18    (srfi srfi-1)
     19    (srfi srfi-9)
     20    (srfi srfi-64)
     21 
     22    (system vm trace)
     23 
     24    (ice-9 match)
     25    (ice-9 pretty-print)
     26 
     27    (sicp utils)
     28    )
     29 
     30   (begin
     31     ;; XXX: In 4.1.3 we see that the procedure `true?` is defined
     32     ;; using the host-variable `false` whose value is 'false, but we
     33     ;; don't see it defined anywhere in the good book, so we need to
     34     ;; define the host-variable false ourselves.
     35     ;;
     36     ;; In MIT Scheme, the one the SICP people seem to love to use for
     37     ;; SICP, the values of `false` and `true` are #f and #t, #f being
     38     ;; the only value that is falsituous and #t there for having a
     39     ;; truthious value that has no other meaning other than being
     40     ;; truthitiousic.
     41     ;;
     42     ;; ```
     43     ;; # `scheme` is the MIT Scheme executable:
     44     ;; $ guix shell mit-scheme -- scheme
     45     ;; MIT/GNU Scheme running under GNU/Linux
     46     ;; Type `^C' (control-C) followed by `H' to obtain information about interrupts.
     47     ;;
     48     ;; Copyright (C) 2020 Massachusetts Institute of Technology
     49     ;; This is free software; see the source for copying conditions. There is NO warranty; not even for
     50     ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     51     ;;
     52     ;; Image saved on Sunday March 7, 2021 at 3:24:56 PM
     53     ;;   Release 11.2 || SF || LIAR/x86-64
     54     ;;
     55     ;; 1 ]=> false
     56     ;;
     57     ;; ;Value: #f
     58     ;;
     59     ;; 1 ]=> true
     60     ;;
     61     ;; ;Value: #t
     62     ;;
     63     ;; 1 ]=>
     64     ;; ```
     65     (define false #f)
     66     (define true #t)
     67 
     68     (define (make-environment vars vals)
     69       "A comfort procedure because calling extend on the-empty-environment is a PITA."
     70       (extend-environment vars
     71                           vals
     72                           the-empty-environment))
     73 
     74     ;; XXX: As described in chapter 4.1.4 note 2, we need to name the
     75     ;; host `apply`, and the guest `apply` differently.  I define the
     76     ;; host's `apply` to be the name used in the book.
     77     (define apply-in-underlying-scheme scheme:base:apply)
     78 
     79 ;;; Start:
     80 
     81 ;;; 4.1.1
     82 
     83     (define *form-table* '())
     84 
     85     (define (add-form-handler! form? handler)
     86       (set! *form-table*
     87             (cons (cons form?
     88                         handler)
     89                   *form-table*)))
     90 
     91     (define (get-form-handler exp)
     92       (let loop ((table *form-table*))
     93         (match table
     94           ('()
     95            (error "Unknown form" exp))
     96           (`((,form? . ,handler) . ,rest)
     97            (if (form? exp)
     98                handler
     99                (loop rest))))))
    100 
    101     (define (eval exp env)
    102       (cond ((self-evaluating? exp)
    103              exp)
    104             ((variable? exp)
    105              (lookup-variable-value exp env))
    106             ((pair? exp)
    107              ((get-form-handler exp) exp env))
    108             (else
    109              (error "Unknown expression type -- EVAL" exp))))
    110 
    111     (define (apply procedure arguments)
    112       (cond ((primitive-procedure? procedure)
    113              (apply-primitive-procedure
    114               procedure
    115               arguments))
    116             ((compound-procedure? procedure)
    117              (eval-sequence
    118               (procedure-body procedure)
    119               (extend-environment
    120                (procedure-parameters
    121                 procedure)
    122                arguments
    123                (procedure-environment
    124                 procedure))))
    125             (else
    126              (error "Unknown procedure type -- APPLY"
    127                     procedure))))
    128 
    129 ;;; Procedure arguments:
    130 
    131     (define (list-of-values exps env)
    132       (if (no-operands? exps)
    133           '()
    134           (cons (eval (first-operand exps) env)
    135                 (list-of-values (rest-operands exps) env))))
    136 
    137 ;;; Conditionals:
    138 
    139     (define (eval-if exp env)
    140       (if (true? (eval (if-predicate exp) env))
    141           (eval (if-consequent exp) env)
    142           (eval (if-alternative exp) env)))
    143 
    144 ;;; Sequences:
    145 
    146     (define (eval-sequence exps env)
    147       (cond ((last-exp? exps)
    148              (eval (first-exp exps) env))
    149             (else
    150              (eval (first-exp exps) env)
    151              (eval-sequence (rest-exps exps)
    152                             env))))
    153 
    154 ;;; Assignments and definitions
    155 
    156     (define (eval-assignment exp env)
    157       (set-variable-value!
    158        (assignment-variable exp)
    159        (eval (assignment-value exp) env)
    160        env)
    161       'ok)
    162 
    163     (define (eval-definition exp env)
    164       (define-variable!
    165         (definition-variable exp)
    166         (eval (definition-value exp) env)
    167         env)
    168       'ok)
    169 
    170 ;;; end 4.1.1
    171 
    172 ;;; 4.1.2
    173 
    174 
    175     (define (self-evaluating? exp)
    176       (cond ((number? exp) true)
    177             ((string? exp) true)
    178             (else false)))
    179 
    180     (define (variable? exp) (symbol? exp))
    181 
    182     (define (quoted? exp)
    183       (tagged-list? exp 'quote))
    184 
    185     (define (text-of-quotation exp)
    186       (cadr exp))
    187 
    188     (define (tagged-list? exp tag)
    189       (if (pair? exp)
    190           (eq? (car exp) tag)
    191           false))
    192 
    193     (define (assignment? exp)
    194       (tagged-list? exp 'set!))
    195 
    196     (define (assignment-variable exp)
    197       (cadr exp))
    198 
    199     (define (assignment-value exp) (caddr exp))
    200 
    201     (define (definition? exp)
    202       (tagged-list? exp 'define))
    203 
    204     (define (definition-variable exp)
    205       (if (symbol? (cadr exp))
    206           (cadr exp)
    207           (caadr exp)))
    208 
    209     (define (definition-value exp)
    210       (if (symbol? (cadr exp))
    211           (caddr exp)
    212           (make-lambda
    213            (cdadr exp)   ; formal-parameters
    214            (cddr exp)))) ; body
    215 
    216     (define (lambda? exp)
    217       (tagged-list? exp 'lambda))
    218     (define (lambda-parameters exp) (cadr exp))
    219     (define (lambda-body exp) (cddr exp))
    220 
    221     (define (make-lambda parameters body)
    222       (cons 'lambda (cons parameters body)))
    223 
    224     (define (if? exp) (tagged-list? exp 'if))
    225     (define (if-predicate exp) (cadr exp))
    226     (define (if-consequent exp) (caddr exp))
    227     (define (if-alternative exp)
    228       (if (not (null? (cdddr exp)))
    229           (cadddr exp)
    230           'false))
    231 
    232     (define (make-if predicate
    233                      consequent
    234                      alternative)
    235       (list 'if
    236             predicate
    237             consequent
    238             alternative))
    239 
    240     (define (begin? exp)
    241       (tagged-list? exp 'begin))
    242     (define (begin-actions exp) (cdr exp))
    243     (define (last-exp? seq) (null? (cdr seq)))
    244     (define (first-exp seq) (car seq))
    245     (define (rest-exps seq) (cdr seq))
    246 
    247     (define (sequence->exp seq)
    248       (cond ((null? seq) seq)
    249             ((last-exp? seq) (first-exp seq))
    250             (else (make-begin seq))))
    251 
    252     (define (make-begin seq) (cons 'begin seq))
    253 
    254     (define (application? exp) (pair? exp))
    255     (define (operator exp) (car exp))
    256     (define (operands exp) (cdr exp))
    257     (define (no-operands? ops) (null? ops))
    258     (define (first-operand ops) (car ops))
    259     (define (rest-operands ops) (cdr ops))
    260 
    261     (define (cond? exp)
    262       (tagged-list? exp 'cond))
    263     (define (cond-clauses exp) (cdr exp))
    264     (define (cond-else-clause? clause)
    265       (eq? (cond-predicate clause) 'else))
    266     (define (cond-predicate clause)
    267       (car clause))
    268     (define (cond-actions clause)
    269       (cdr clause))
    270     (define (cond->if exp)
    271       (expand-clauses (cond-clauses exp)))
    272     (define (expand-clauses clauses)
    273       (match clauses
    274         ('() 'false)
    275         ((('else actions ...))
    276          (sequence->exp actions))
    277         ((('else actions ...) rest ...)
    278          (error "ELSE clause isn't last: COND->IF"
    279                 clauses))
    280         (((predicate '=> recipient) rest ...)
    281          `((lambda (value)
    282              (if value
    283                  (,recipient value)
    284                  ,(expand-clauses rest)))
    285            ,predicate))
    286         (((predicate actions ...) rest ...)
    287          (make-if predicate
    288                   (sequence->exp actions)
    289                   (expand-clauses rest)))
    290         (otherwise
    291          (error "-- EXPAND-CLAUSES" clauses))))
    292 
    293     (define (let->combination exp)
    294       (match exp
    295         (('let (var-exps ...)
    296            body ...)
    297          (let ((vars (map car var-exps))
    298                (exps (map cadr var-exps)))
    299            (eval `((lambda ,vars
    300                      ,@body)
    301                    ,@exps)
    302                  env)))))
    303 
    304 ;;; end 4.1.2
    305 
    306 ;;; 4.1.3
    307 
    308     ;; XXX: By default, false's value is #f, which is the only true
    309     ;; false.  All others are fake and would have the truthitousness
    310     ;; property.  Consult `info r7rs-small` or `C-h
    311     (define (true? x)
    312       (not (eq? x false)))
    313 
    314     (define (false? x)
    315       (eq? x false))
    316 
    317     (define (make-procedure parameters body env)
    318       (list 'procedure parameters body env))
    319     (define (compound-procedure? p)
    320       (tagged-list? p 'procedure))
    321     (define (procedure-parameters p) (cadr p))
    322     (define (procedure-body p) (caddr p))
    323     (define (procedure-environment p) (cadddr p))
    324 
    325     (define (enclosing-environment env) (cdr env))
    326     (define (first-frame env) (car env))
    327     (define the-empty-environment '())
    328 
    329     (define (make-frame variables values)
    330       (cons variables values))
    331     (define (frame-variables frame) (car frame))
    332     (define (frame-values frame) (cdr frame))
    333     (define (add-binding-to-frame! var val frame)
    334       (set-car! frame (cons var (car frame)))
    335       (set-cdr! frame (cons val (cdr frame))))
    336 
    337     (define (extend-environment vars vals base-env)
    338       (if (= (length vars) (length vals))
    339           (cons (make-frame vars vals) base-env)
    340           (if (< (length vars) (length vals))
    341               (error "Too many arguments supplied"
    342                      vars
    343                      vals)
    344               (error "Too few arguments supplied"
    345                      vars
    346                      vals))))
    347 
    348     (define (lookup-variable-value var env)
    349       (define (env-loop env)
    350         (define (scan vars vals)
    351           (cond ((null? vars)
    352                  (env-loop
    353                   (enclosing-environment env)))
    354                 ((eq? var (car vars))
    355                  (car vals))
    356                 (else (scan (cdr vars)
    357                             (cdr vals)))))
    358         (if (eq? env the-empty-environment)
    359             (error "Unbound variable -- LOOKUP-VARIABLE-VALUE" var)
    360             (let ((frame (first-frame env)))
    361               (scan (frame-variables frame)
    362                     (frame-values frame)))))
    363       (env-loop env))
    364 
    365     (define (set-variable-value! var val env)
    366       ;; XXX: Just trying to see what it would look like if I just used named lets.
    367       ;;
    368       ;; (let loop-over-environments ((env env))
    369       ;;   (cond
    370       ;;    ((eq? env the-empty-enviornment)
    371       ;;     (error "Unbound variable: SET!" var))
    372       ;;    (else
    373       ;;     (let ((frame (first-frame env)))
    374       ;;       (let loop-over-frame ((vars (frame-variables frame))
    375       ;;                             (vals (frame-values frame)))
    376       ;;         (cond
    377       ;;          ((null? vars)
    378       ;;           (loop-over-environments (enclosing-environment env)))
    379       ;;          ((eq? var (car vars))
    380       ;;           (set-car! vals val))
    381       ;;          (else
    382       ;;           (loop-over-frame ((cdr vars)
    383       ;;                             (cdr vals))))))))))
    384 
    385       (define (env-loop env)
    386         (define (scan vars vals)
    387           (cond ((null? vars)
    388                  (env-loop
    389                   (enclosing-environment env)))
    390                 ((eq? var (car vars))
    391                  (set-car! vals val))
    392                 (else (scan (cdr vars)
    393                             (cdr vals)))))
    394         (if (eq? env the-empty-environment)
    395             (error "Unbound variable: SET!" var)
    396             (let ((frame (first-frame env)))
    397               (scan (frame-variables frame)
    398                     (frame-values frame)))))
    399       (env-loop env))
    400 
    401     (define (define-variable! var val env)
    402       "Add a new variable VAR with value VAL in the top frame of environment ENV.
    403 
    404 If variable VAR already exists in the top frame, set VAR in the top
    405 frame to VAL."
    406 
    407       ;; We will CHANGE (why did I all uppercase "CHANGE" here?  I
    408       ;; don't remember.  Maybe it is some sort of a joke?) only
    409       ;; the first frame.
    410       (let ((frame (first-frame env)))
    411         (define (scan vars vals)
    412           (cond ((null? vars)
    413                  (add-binding-to-frame!
    414                   var val frame))
    415                 ((eq? var (car vars))
    416                  (set-car! vals val))
    417                 (else (scan (cdr vars)
    418                             (cdr vals)))))
    419         (scan (frame-variables frame)
    420               (frame-values frame))))
    421 
    422 ;;; 4.1.4
    423 
    424     (define (setup-environment)
    425       (dpp 'moo)
    426       (let* (;; XXX: See bug below on the quoted (define
    427              ;; primitive-procedures ...)
    428              (primitive-procedures
    429               (list (list 'car car)
    430                     (list 'cdr cdr)
    431                     (list 'cons cons)
    432                     (list 'null? null?)
    433                     (list '+ +)
    434                     (list '- -)
    435                     (list '* *)
    436                     (list '/ /)
    437                     (list '= =)
    438                     (list 'display display)
    439                     (list 'write write)
    440                     (list 'read read)))
    441              (initial-env
    442               (extend-environment
    443                (primitive-procedure-names primitive-procedures)
    444                (primitive-procedure-objects primitive-procedures)
    445                the-empty-environment)))
    446         (define-variable! 'true true initial-env)
    447         (define-variable! 'false false initial-env)
    448         initial-env))
    449 
    450     (define the-global-environment
    451       (begin
    452         (dpp 'moo)
    453         (setup-environment)))
    454 
    455     (define (primitive-procedure? proc)
    456       (tagged-list? proc 'primitive))
    457 
    458     (define (primitive-implementation proc)
    459       (cadr proc))
    460 
    461     ;; XXX: There is a bug here in SICP or GNU Guile or both.
    462     ;; primitive-procedures is `#<unspecified>` when this library is
    463     ;; being loaded.
    464     '(define primitive-procedures
    465        (list (list 'car car)
    466              (list 'cdr cdr)
    467              (list 'cons cons)
    468              (list 'null? null?)
    469              (list '+ +)
    470              (list '- -)
    471              (list '* *)
    472              (list '/ /)
    473              (list 'display display)
    474              (list 'write write)
    475              (list 'read read)))
    476 
    477     (define (primitive-procedure-names primitive-procedures)
    478       (map car
    479            primitive-procedures))
    480 
    481     (define (primitive-procedure-objects primitive-procedures)
    482       (map (lambda (proc)
    483              (list 'primitive (cadr proc)))
    484            primitive-procedures))
    485 
    486     (define (apply-primitive-procedure proc args)
    487       (apply-in-underlying-scheme
    488        (primitive-implementation proc) args))
    489 
    490     (define input-prompt  ";;; M-Eval input:")
    491     (define output-prompt ";;; M-Eval value:")
    492 
    493     (define (driver-loop)
    494       (prompt-for-input input-prompt)
    495       (let ((input (read)))
    496         (let ((output
    497                (eval input
    498                      the-global-environment)))
    499           (announce-output output-prompt)
    500           (user-print output)))
    501       (driver-loop))
    502 
    503     (define (prompt-for-input string)
    504       (newline) (newline)
    505       (display string) (newline))
    506 
    507     (define (announce-output string)
    508       (newline) (display string) (newline))
    509 
    510     (define (user-print object)
    511       (if (compound-procedure? object)
    512           (display
    513            (list 'compound-procedure
    514                  (procedure-parameters object)
    515                  (procedure-body object)
    516                  '<procedure-env>))
    517           (display object)))
    518 
    519     ;; XXX: Already defined above:
    520     ;; (define the-global-environment
    521     ;;   (setup-environment))
    522 
    523     (define (main args)
    524       (match args
    525         ('()
    526          (error "Arguments should have something rather than nothing."))
    527         (`(,arg0)
    528          (display arg0)
    529          (newline))
    530         (`(,arg0 "--debug")
    531          (display "DEBUG TURN ON!\n")
    532          (set! *debug* #t))
    533         (args (error "Unknown arguments:" args)))
    534 
    535       (driver-loop))
    536 
    537     (define (run-internal-tests)
    538       (test-eq 1
    539         (lookup-variable-value 'a
    540                                (extend-environment '(a +)
    541                                                    `(1 ,+)
    542                                                    the-empty-environment)))
    543       (test-eq 1
    544         (lookup-variable-value 'a
    545                                (extend-environment '(+ a)
    546                                                    `(,+ 1)
    547                                                    the-empty-environment)))
    548       (test-eq +
    549         (lookup-variable-value '+
    550                                (extend-environment '(a +)
    551                                                    `(1 ,+)
    552                                                    the-empty-environment))))
    553 
    554     (add-form-handler! application?
    555                        (lambda (exp env)
    556                          (apply (eval (operator exp) env)
    557                                 (list-of-values
    558                                  (operands exp)
    559                                  env))))
    560     (add-form-handler! (lambda (exp)
    561                          (tagged-list? exp 'or))
    562                        (lambda (exp env)
    563                          (eval (let loop ((seq (cdr exp)))
    564                                  (match seq
    565                                    ('() 'false)
    566                                    ((expression . rest)
    567                                     (list (list 'lambda (list 'value)
    568                                                 (list 'if
    569                                                       'value
    570                                                       'value
    571                                                       (loop rest)))
    572                                           expression))
    573                                    (otherwise
    574                                     (error "Weird expression -- AND"
    575                                            otherwise))))
    576                                env)))
    577     (add-form-handler! (lambda (exp)
    578                          (tagged-list? exp 'and))
    579                        (lambda (exp env)
    580                          (eval (let loop ((seq (cdr exp)))
    581                                  (match seq
    582                                    ('() 'false)
    583                                    ((expression)
    584                                     `((lambda (value)
    585                                         (if value
    586                                             value
    587                                             false))
    588                                       ,expression)
    589                                     )
    590                                    ((expression . rest)
    591                                     `((lambda (value)
    592                                         (if value
    593                                             ,(loop rest)
    594                                             false))
    595                                       ,expression))
    596                                    (otherwise
    597                                     (error "Weird expression -- AND"
    598                                            otherwise))))
    599                                env)))
    600     (add-form-handler! cond?
    601                        (lambda (exp env)
    602                          (eval (cond->if exp) env)))
    603     (add-form-handler! begin?
    604                        (lambda (exp env)
    605                          (eval-sequence
    606                           (begin-actions exp)
    607                           env)))
    608     (add-form-handler! lambda?
    609                        (lambda (exp env)
    610                          (make-procedure (lambda-parameters exp)
    611                                          (lambda-body exp)
    612                                          env)))
    613     (add-form-handler! if? eval-if)
    614     (add-form-handler! definition? eval-definition)
    615     (add-form-handler! assignment? eval-assignment)
    616     (add-form-handler! quoted? (lambda (exp env) (text-of-quotation exp)))
    617     (add-form-handler! (lambda (exp) (tagged-list? exp 'let))
    618                        (lambda (exp env)
    619                          (eval (let->combination exp) env)))
    620 
    621     ))