Guest User

Untitled

a guest
Dec 13th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. #lang racket
  2.  
  3. (struct mbox ([v #:mutable]))
  4.  
  5. (define (box x) (mbox x))
  6.  
  7. (define (unbox x)
  8. (cond [(ip? x)
  9. (define imp? (vector-ref (ip-m x) 2))
  10. (define ub (vector-ref (ip-m x) 0))
  11. (define val (mbox-v x))
  12. (define res (ub x val))
  13. (unless (or imp? (chaperone-of? res val))
  14. (error 'fail))
  15. res]
  16. [else (mbox-v x)]))
  17.  
  18. (define (set-box! x v)
  19. (cond [(ip? x)
  20. (define imp? (vector-ref (ip-m x) 2))
  21. (define sb! (vector-ref (ip-m x) 1))
  22. (define val (sb! x v))
  23. (unless (or imp? (chaperone-of? val v))
  24. (error 'fail))
  25. (set-mbox-v! x val)]
  26. [else (set-mbox-v! x v)]))
  27.  
  28. (define (box? x) (mbox? x))
  29.  
  30. (define-values (ip ip? ip-m)
  31. (make-impersonator-property 'mbox-chaperone))
  32.  
  33. (define (chaperone-box b ub sb! . args)
  34. (apply chaperone-struct b set-mbox-v! (λ (a b) b) ip (vector ub sb! #f) args))
  35. (define (impersonate-box b ub sb! . args)
  36. (apply impersonate-struct b set-mbox-v! (λ (a b) b) ip (vector ub sb! #t) args))
  37.  
  38. (provide box box? unbox set-box! chaperone-box impersonate-box)
  39.  
  40.  
  41. (module+ test
  42. (require rackunit)
  43. (check-equal? (unbox (box 3)) 3)
  44. (check-equal? (unbox (chaperone-box (box 3) (λ (a b) b) (λ (a b) b))) 3)
  45. (check-equal? (unbox (impersonate-box (box 3) (λ (a b) b) (λ (a b) b))) 3)
  46. (check-equal? (unbox (impersonate-box (box 3)
  47. (λ (a b) 4)
  48. (λ (a b) b)))
  49. 4)
  50. ;; this should error
  51. (check-exn exn:fail?
  52. (λ _ (unbox (chaperone-box (box 3)
  53. (λ (a b) 4)
  54. (λ (a b) b))))))
Add Comment
Please, Sign In to add comment