Advertisement
Void-voiD

Untitled

Dec 7th, 2018
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 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-syntax match
  29. (syntax-rules ()
  30. ((_ true x . xx) (match true x xx))
  31. ((_ true ((name arg ...) expr) other)
  32. (if (equal? name (vector-ref true 1))
  33. (apply (lambda (arg ...) expr) (cddr (vector->list true)))
  34. (match true (car other) (cdr other))))))
  35.  
  36. (begin
  37. (define-data figure ((square a)
  38. (rectangle a b)
  39. (triangle a b c)
  40. (circle r)))
  41.  
  42. (define s (square 10))
  43. (define r (rectangle 10 20))
  44. (define t (triangle 10 20 30))
  45. (define c (circle 10))
  46.  
  47. (define test-1 (and (figure? s)
  48. (figure? r)
  49. (figure? t)
  50. (figure? c)))
  51.  
  52. (define a '(circle 0 0 1))
  53. (define b #f)
  54.  
  55. (define test-2 (and (figure? a)
  56. (figure? b)))
  57.  
  58. (define pi (acos -1))
  59.  
  60. (define (perim f)
  61. (match f
  62. ((square a) (* 4 a))
  63. ((rectangle a b) (* 2 (+ a b)))
  64. ((triangle a b c) (+ a b c))
  65. ((circle r) (* 2 pi r))))
  66.  
  67. (list test-1
  68. test-2
  69. (perim s)
  70. (perim r)
  71. (perim t)
  72. (round (perim c)))
  73. ) ; end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement