rep.scm

((カッコつけてる)30分プログラム)、(その23)。

Schemeで実装したScheme風言語。SICPの超言語抽象(meta laungage abstraction)。

$ gosh rep.scm
>(set! a 10)
#<undef>
>(+ a 5)
15
>(set! b (* a 2))
#<undef>
>b
20
(define (my-eval exp env)
  (cond
   ;; set!
   ((and (pair? exp) (eq? (car exp) 'set!) (eq? (length exp) 3))
    (hash-table-put! env (cadr exp) (my-eval (caddr exp) env)))

   ;; variable ref
   ((and (symbol? exp) (hash-table-exists? env exp))
    (hash-table-get env exp))

   ;; func call
   ((and (pair? exp))
    (let1 evaled (map (lambda(e) (my-eval e env)) exp)
	  (apply (car evaled) (cdr evaled))))

   ;; other(deletage to scheme)
   (else (eval exp (scheme-report-environment 5)))))
 
(define (loop env)
  (while #t
	 (display ">")
	 (flush)
	 (print (my-eval (read) env))))
 
(define (main args)
  (loop (make-hash-table)))
  • read-eval-print-loopを使いたかったけど、環境の扱い方が分からなかった
  • readがEOFを返したら終了、という動作にしたかった。でも、eofかどうかを調べる方法がわかんなかった
  • 結構大変であまりしっかり実装できなかった