i6.scm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #lang racket
  2. (require racket/match)
  3. (define builtins
  4. `((car . ,car)
  5. (cdr . ,cdr)
  6. (cons . ,cons)
  7. (list . ,list)
  8. (list . ,list?)
  9. (null? . ,null?)
  10. (+ . ,+)
  11. (- . ,-)
  12. (* . ,*)
  13. (/ . ,/)
  14. (= . ,=)
  15. (eq? . ,eq?)
  16. (equal? . ,equal?)
  17. (not . ,not)
  18. ;;
  19. (display . ,display)
  20. (newline . ,newline)
  21. (print . ,(lambda (s) (display s) (newline)))
  22. ))
  23. (define special-forms
  24. '(lambda if quote begin and or))
  25. (define (ex prg builtins spec)
  26. ;; a program is a list of definitions
  27. (if (null? prg)
  28. #t
  29. (match (car prg)
  30. (`(define ,name ,source)
  31. (let ((value (i source builtins spec)))
  32. (ex (cdr prg)
  33. (cons (cons name value) builtins)
  34. (remove name spec)))))))
  35. (define (i exp env spec)
  36. (cond ((number? exp) exp)
  37. ((boolean? exp) exp)
  38. ((symbol? exp)
  39. (cond ((assoc exp env) => cdr)
  40. (else (error "unbound variable" exp))))
  41. ((list? exp)
  42. (if (member (car exp) spec)
  43. (i-special exp env spec)
  44. (apply (i (car exp) env spec)
  45. (map (lambda (exp) (i exp env spec)) (cdr exp)))))
  46. (else (error "unknown expression type" exp))))
  47. (define (i-special exp env spec)
  48. (match exp
  49. (`(if ,t ,c ,a)
  50. (if (i t env spec)
  51. (i c env spec)
  52. (i a env spec)))
  53. (`(lambda (,x) ,b)
  54. (lambda (y)
  55. (i b (cons (cons x y) env) (remove x spec))))
  56. (`(quote ,d)
  57. d)
  58. (`(begin)
  59. (error "bad begin"))
  60. (`(begin ,thing . ,things)
  61. (let loop ((thing thing) (things things))
  62. (if (null? things)
  63. (i thing env spec)
  64. (begin
  65. (i thing env spec)
  66. (loop (car things) (cdr things))))))
  67. (`(and . ,things)
  68. (let loop ((things things))
  69. (if (null? things)
  70. #t
  71. (if (i (car things) env spec)
  72. (loop (cdr things))
  73. #f))))
  74. (`(or . ,things)
  75. (let loop ((things things))
  76. (if (null? things)
  77. #f
  78. (if (i (car things) env spec)
  79. #t
  80. (loop (cdr things))))))
  81. (else (error "Unimplemented special form:" exp))))
  82. (define t1
  83. (list '(define n1 1)
  84. '(define n2 2)
  85. '(define n3 (+ n1 n2))
  86. '(define f (lambda (x) (* x x)))
  87. '(define main (print (f n3)))))
  88. ;; > (i '(begin (print 1) (print 2) (print 3)) builtins special-forms)
  89. ;; 1
  90. ;; 2
  91. ;; 3
  92. ;; > (ex t1 builtins special-forms)
  93. ;; 9
  94. ;; #t