learning-sicp

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

exercise-7.scm (20486B)


      1 (define-library (sicp solutions chapter-4 exercise-7)
      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            `((lambda ,vars
    300                ,@body)
    301              ,@exps)))))
    302 
    303     (define (let*->nested-lets exp)
    304       (match exp
    305         (('let* ()
    306            body ...)
    307          (make-begin body))
    308         (`(let* ((,var ,exp) . ,rest-of-var-exps)
    309            . ,body)
    310          `(let ((,var ,exp))
    311             ,(let*->nested-lets
    312               `(let* ,rest-of-var-exps
    313                  ,@body))))))
    314 
    315 ;;; end 4.1.2
    316 
    317 ;;; 4.1.3
    318 
    319     ;; XXX: By default, false's value is #f, which is the only true
    320     ;; false.  All others are fake and would have the truthitousness
    321     ;; property.  Consult `info r7rs-small` or `C-h
    322     (define (true? x)
    323       (not (eq? x false)))
    324 
    325     (define (false? x)
    326       (eq? x false))
    327 
    328     (define (make-procedure parameters body env)
    329       (list 'procedure parameters body env))
    330     (define (compound-procedure? p)
    331       (tagged-list? p 'procedure))
    332     (define (procedure-parameters p) (cadr p))
    333     (define (procedure-body p) (caddr p))
    334     (define (procedure-environment p) (cadddr p))
    335 
    336     (define (enclosing-environment env) (cdr env))
    337     (define (first-frame env) (car env))
    338     (define the-empty-environment '())
    339 
    340     (define (make-frame variables values)
    341       (cons variables values))
    342     (define (frame-variables frame) (car frame))
    343     (define (frame-values frame) (cdr frame))
    344     (define (add-binding-to-frame! var val frame)
    345       (set-car! frame (cons var (car frame)))
    346       (set-cdr! frame (cons val (cdr frame))))
    347 
    348     (define (extend-environment vars vals base-env)
    349       (if (= (length vars) (length vals))
    350           (cons (make-frame vars vals) base-env)
    351           (if (< (length vars) (length vals))
    352               (error "Too many arguments supplied"
    353                      vars
    354                      vals)
    355               (error "Too few arguments supplied"
    356                      vars
    357                      vals))))
    358 
    359     (define (lookup-variable-value var env)
    360       (define (env-loop env)
    361         (define (scan vars vals)
    362           (cond ((null? vars)
    363                  (env-loop
    364                   (enclosing-environment env)))
    365                 ((eq? var (car vars))
    366                  (car vals))
    367                 (else (scan (cdr vars)
    368                             (cdr vals)))))
    369         (if (eq? env the-empty-environment)
    370             (error "Unbound variable -- LOOKUP-VARIABLE-VALUE" var)
    371             (let ((frame (first-frame env)))
    372               (scan (frame-variables frame)
    373                     (frame-values frame)))))
    374       (env-loop env))
    375 
    376     (define (set-variable-value! var val env)
    377       ;; XXX: Just trying to see what it would look like if I just used named lets.
    378       ;;
    379       ;; (let loop-over-environments ((env env))
    380       ;;   (cond
    381       ;;    ((eq? env the-empty-enviornment)
    382       ;;     (error "Unbound variable: SET!" var))
    383       ;;    (else
    384       ;;     (let ((frame (first-frame env)))
    385       ;;       (let loop-over-frame ((vars (frame-variables frame))
    386       ;;                             (vals (frame-values frame)))
    387       ;;         (cond
    388       ;;          ((null? vars)
    389       ;;           (loop-over-environments (enclosing-environment env)))
    390       ;;          ((eq? var (car vars))
    391       ;;           (set-car! vals val))
    392       ;;          (else
    393       ;;           (loop-over-frame ((cdr vars)
    394       ;;                             (cdr vals))))))))))
    395 
    396       (define (env-loop env)
    397         (define (scan vars vals)
    398           (cond ((null? vars)
    399                  (env-loop
    400                   (enclosing-environment env)))
    401                 ((eq? var (car vars))
    402                  (set-car! vals val))
    403                 (else (scan (cdr vars)
    404                             (cdr vals)))))
    405         (if (eq? env the-empty-environment)
    406             (error "Unbound variable: SET!" var)
    407             (let ((frame (first-frame env)))
    408               (scan (frame-variables frame)
    409                     (frame-values frame)))))
    410       (env-loop env))
    411 
    412     (define (define-variable! var val env)
    413       "Add a new variable VAR with value VAL in the top frame of environment ENV.
    414 
    415 If variable VAR already exists in the top frame, set VAR in the top
    416 frame to VAL."
    417 
    418       ;; We will CHANGE (why did I all uppercase "CHANGE" here?  I
    419       ;; don't remember.  Maybe it is some sort of a joke?) only
    420       ;; the first frame.
    421       (let ((frame (first-frame env)))
    422         (define (scan vars vals)
    423           (cond ((null? vars)
    424                  (add-binding-to-frame!
    425                   var val frame))
    426                 ((eq? var (car vars))
    427                  (set-car! vals val))
    428                 (else (scan (cdr vars)
    429                             (cdr vals)))))
    430         (scan (frame-variables frame)
    431               (frame-values frame))))
    432 
    433 ;;; 4.1.4
    434 
    435     (define (setup-environment)
    436       (let* (;; XXX: See bug below on the quoted (define
    437              ;; primitive-procedures ...)
    438              (primitive-procedures
    439               (list (list 'car car)
    440                     (list 'cdr cdr)
    441                     (list 'cons cons)
    442                     (list 'null? null?)
    443                     (list '+ +)
    444                     (list '- -)
    445                     (list '* *)
    446                     (list '/ /)
    447                     (list '= =)
    448                     (list 'display display)
    449                     (list 'write write)
    450                     (list 'read read)))
    451              (initial-env
    452               (extend-environment
    453                (primitive-procedure-names primitive-procedures)
    454                (primitive-procedure-objects primitive-procedures)
    455                the-empty-environment)))
    456         (define-variable! 'true true initial-env)
    457         (define-variable! 'false false initial-env)
    458         initial-env))
    459 
    460     (define the-global-environment
    461       (setup-environment))
    462 
    463     (define (primitive-procedure? proc)
    464       (tagged-list? proc 'primitive))
    465 
    466     (define (primitive-implementation proc)
    467       (cadr proc))
    468 
    469     ;; XXX: There is a bug here in SICP or GNU Guile or both.
    470     ;; primitive-procedures is `#<unspecified>` when this library is
    471     ;; being loaded.
    472     '(define primitive-procedures
    473        (list (list 'car car)
    474              (list 'cdr cdr)
    475              (list 'cons cons)
    476              (list 'null? null?)
    477              (list '+ +)
    478              (list '- -)
    479              (list '* *)
    480              (list '/ /)
    481              (list 'display display)
    482              (list 'write write)
    483              (list 'read read)))
    484 
    485     (define (primitive-procedure-names primitive-procedures)
    486       (map car
    487            primitive-procedures))
    488 
    489     (define (primitive-procedure-objects primitive-procedures)
    490       (map (lambda (proc)
    491              (list 'primitive (cadr proc)))
    492            primitive-procedures))
    493 
    494     (define (apply-primitive-procedure proc args)
    495       (apply-in-underlying-scheme
    496        (primitive-implementation proc) args))
    497 
    498     (define input-prompt  ";;; M-Eval input:")
    499     (define output-prompt ";;; M-Eval value:")
    500 
    501     (define (driver-loop)
    502       (prompt-for-input input-prompt)
    503       (let ((input (read)))
    504         (let ((output
    505                (eval input
    506                      the-global-environment)))
    507           (announce-output output-prompt)
    508           (user-print output)))
    509       (driver-loop))
    510 
    511     (define (prompt-for-input string)
    512       (newline) (newline)
    513       (display string) (newline))
    514 
    515     (define (announce-output string)
    516       (newline) (display string) (newline))
    517 
    518     (define (user-print object)
    519       (if (compound-procedure? object)
    520           (display
    521            (list 'compound-procedure
    522                  (procedure-parameters object)
    523                  (procedure-body object)
    524                  '<procedure-env>))
    525           (display object)))
    526 
    527     ;; XXX: Already defined above:
    528     ;; (define the-global-environment
    529     ;;   (setup-environment))
    530 
    531     (define (main args)
    532       (match args
    533         ('()
    534          (error "Arguments should have something rather than nothing."))
    535         (`(,arg0)
    536          (display arg0)
    537          (newline))
    538         (`(,arg0 "--debug")
    539          (display "DEBUG TURN ON!\n")
    540          (set! *debug* #t))
    541         (args (error "Unknown arguments:" args)))
    542 
    543       (driver-loop))
    544 
    545     (define (run-internal-tests)
    546       (test-eq 1
    547         (lookup-variable-value 'a
    548                                (extend-environment '(a +)
    549                                                    `(1 ,+)
    550                                                    the-empty-environment)))
    551       (test-eq 1
    552         (lookup-variable-value 'a
    553                                (extend-environment '(+ a)
    554                                                    `(,+ 1)
    555                                                    the-empty-environment)))
    556       (test-eq +
    557         (lookup-variable-value '+
    558                                (extend-environment '(a +)
    559                                                    `(1 ,+)
    560                                                    the-empty-environment))))
    561 
    562     (add-form-handler! application?
    563                        (lambda (exp env)
    564                          (apply (eval (operator exp) env)
    565                                 (list-of-values
    566                                  (operands exp)
    567                                  env))))
    568     (add-form-handler! (lambda (exp)
    569                          (tagged-list? exp 'or))
    570                        (lambda (exp env)
    571                          (eval (let loop ((seq (cdr exp)))
    572                                  (match seq
    573                                    ('() 'false)
    574                                    ((expression . rest)
    575                                     (list (list 'lambda (list 'value)
    576                                                 (list 'if
    577                                                       'value
    578                                                       'value
    579                                                       (loop rest)))
    580                                           expression))
    581                                    (otherwise
    582                                     (error "Weird expression -- AND"
    583                                            otherwise))))
    584                                env)))
    585     (add-form-handler! (lambda (exp)
    586                          (tagged-list? exp 'and))
    587                        (lambda (exp env)
    588                          (eval (let loop ((seq (cdr exp)))
    589                                  (match seq
    590                                    ('() 'false)
    591                                    ((expression)
    592                                     `((lambda (value)
    593                                         (if value
    594                                             value
    595                                             false))
    596                                       ,expression)
    597                                     )
    598                                    ((expression . rest)
    599                                     `((lambda (value)
    600                                         (if value
    601                                             ,(loop rest)
    602                                             false))
    603                                       ,expression))
    604                                    (otherwise
    605                                     (error "Weird expression -- AND"
    606                                            otherwise))))
    607                                env)))
    608     (add-form-handler! cond?
    609                        (lambda (exp env)
    610                          (eval (cond->if exp) env)))
    611     (add-form-handler! begin?
    612                        (lambda (exp env)
    613                          (eval-sequence
    614                           (begin-actions exp)
    615                           env)))
    616     (add-form-handler! lambda?
    617                        (lambda (exp env)
    618                          (make-procedure (lambda-parameters exp)
    619                                          (lambda-body exp)
    620                                          env)))
    621     (add-form-handler! if? eval-if)
    622     (add-form-handler! definition? eval-definition)
    623     (add-form-handler! assignment? eval-assignment)
    624     (add-form-handler! quoted? (lambda (exp env) (text-of-quotation exp)))
    625     (add-form-handler! (lambda (exp) (tagged-list? exp 'let))
    626                        (lambda (exp env)
    627                          (eval (let->combination exp) env)))
    628     (add-form-handler! (lambda (exp) (tagged-list? exp 'let*))
    629                        (lambda (exp env)
    630                          (eval (let*->nested-lets exp) env)))
    631 
    632     ))