reroot.scm 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ; Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. ; Authors: Richard Kelsey, Jonathan Rees
  3. ; A state space is a tree with the state at the root. Each node other
  4. ; than the root is a triple <before, after, parent>, represented in
  5. ; this implementation as a structure ((before . after) . parent).
  6. ; Moving from one state to another means re-rooting the tree by pointer
  7. ; reversal.
  8. (define *here* (list #f))
  9. (define original-cwcc call-with-current-continuation)
  10. (define (call-with-current-continuation proc)
  11. (let ((here *here*))
  12. (original-cwcc (lambda (cont)
  13. (proc (lambda results
  14. (reroot! here)
  15. (apply cont results)))))))
  16. (define (dynamic-wind before during after)
  17. (let ((here *here*))
  18. (reroot! (cons (cons before after) here))
  19. (call-with-values during
  20. (lambda results
  21. (reroot! here)
  22. (apply values results)))))
  23. (define (reroot! there)
  24. (if (not (eq? *here* there))
  25. (begin (reroot! (cdr there))
  26. (let ((before (caar there))
  27. (after (cdar there)))
  28. (set-car! *here* (cons after before))
  29. (set-cdr! *here* there)
  30. (set-car! there #f)
  31. (set-cdr! there '())
  32. (set! *here* there)
  33. (before)))))
  34. ; -----
  35. ;
  36. ;(define r #f) (define s #f) (define (p x) (write x) (newline))
  37. ;(define (tst)
  38. ; (set! r *here*)
  39. ; (set! s (cons (cons (lambda () (p 'in)) (lambda () (p 'out))) *here*))
  40. ; (reroot! s))
  41. ;
  42. ;
  43. ;(define (check) ;Algorithm invariants
  44. ; (if (not (null? (cdr *here*)))
  45. ; (assertion-violation 'check "confusion #1"))
  46. ; (if (car *here*)
  47. ; (assertion-violation 'check "confusion #2")))