Advertisement
Void-voiD

Untitled

Dec 7th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. (define-syntax trace
  2. (syntax-rules ()
  3. ((trace x)
  4. (begin
  5. (write (quote x))
  6. (display " => ")
  7. (write x)
  8. (newline)
  9. x))))
  10.  
  11. (define (super-cons x res)
  12. (if (null? x)
  13. (reverse res)
  14. (super-cons (cdr x) (cons (car x) res))))
  15.  
  16. (define-syntax define-data
  17. (syntax-rules ()
  18. ((_ type (arg . args))
  19. (begin
  20. (for-each (lambda (i)
  21. (begin
  22. (eval `(define (,(car i) x . xx)
  23. (list->vector (cons 'type (cons ',(car i) (cons x (super-cons xx '())))))) (interaction-environment)))) (cons 'arg 'args))
  24. (eval `(define (,(string->symbol (string-append (symbol->string 'type) (symbol->string '?))) x)
  25. (and (vector? x) (equal? 'type (vector-ref x 0)) (> (vector-length x) 2))) (interaction-environment))
  26. ))))
  27.  
  28. (define (solve val def expr)
  29. (for-each (lambda (i) (begin
  30. (eval `(define ,i ,(car val)) (interaction-environment))
  31. (set! val (cdr val)))) def)
  32. (eval expr (interaction-environment)))
  33.  
  34. (define (search true list)
  35. (let ((cur (caar list)))
  36. (if (and (list? cur) (equal? (car cur) (vector-ref true 1)) (= (length cur) (- (vector-length true) 1)))
  37. (let ((val (cddr (vector->list true)))
  38. (def (cdr cur))
  39. (expr (cadr (car list))))
  40. (solve val def expr))
  41. (search true (cdr list)))))
  42.  
  43. (define-syntax match
  44. (syntax-rules ()
  45. ((_ true arg . args)
  46. (search true (cons 'arg 'args)))))
  47.  
  48. (begin
  49. (define-data figure ((square a)
  50. (rectangle a b)
  51. (triangle a b c)
  52. (circle r)))
  53.  
  54. (define s (square 10))
  55. (define r (rectangle 10 20))
  56. (define t (triangle 10 20 30))
  57. (define c (circle 10))
  58.  
  59. (define test-1 (and (figure? s)
  60. (figure? r)
  61. (figure? t)
  62. (figure? c)))
  63.  
  64. (define a '(circle 0 0 1))
  65. (define b #f)
  66.  
  67. (define test-2 (and (figure? a)
  68. (figure? b)))
  69.  
  70. (define pi (acos -1))
  71.  
  72. (define (perim f)
  73. (match f
  74. ((square a) (* 4 a))
  75. ((rectangle a b) (* 2 (+ a b)))
  76. ((triangle a b c) (+ a b c))
  77. ((circle r) (* 2 pi r))))
  78.  
  79. (list test-1
  80. test-2
  81. (perim s)
  82. (perim r)
  83. (perim t)
  84. (round (perim c)))
  85. ) ; end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement