Advertisement
Void-voiD

Untitled

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