fork download
  1. ; nth item in binary search tree
  2. ; tree is null list, or a list of item, lkid, rkid
  3.  
  4. (define (range . args)
  5. (case (length args)
  6. ((1) (range 0 (car args) (if (negative? (car args)) -1 1)))
  7. ((2) (range (car args) (cadr args) (if (< (car args) (cadr args)) 1 -1)))
  8. ((3) (let ((le? (if (negative? (caddr args)) >= <=)))
  9. (let loop ((x(car args)) (xs '()))
  10. (if (le? (cadr args) x)
  11. (reverse xs)
  12. (loop (+ x (caddr args)) (cons x xs))))))
  13. (else (error 'range "unrecognized arguments"))))
  14.  
  15. (define (insert lt? x tree)
  16. (cond ((null? tree)
  17. (list x (list) (list)))
  18. ((lt? x (car tree))
  19. (list (car tree) (insert lt? x (cadr tree)) (caddr tree)))
  20. ((lt? (car tree) x)
  21. (list (car tree) (cadr tree) (insert lt? x (caddr tree))))
  22. (else tree)))
  23.  
  24. (define (member? lt? x tree)
  25. (cond ((null? tree) #f)
  26. ((lt? x (car tree)) (member? lt? x (cadr tree)))
  27. ((lt? (car tree) x) (member? lt? x (caddr tree)))
  28. (else #t)))
  29.  
  30. (define tree (insert < 4 (insert < 6 (insert < 0 (insert < 7
  31. (insert < 1 (insert < 5 (insert < 2 (insert < 3 (list))))))))))
  32.  
  33. (display tree) (newline)
  34.  
  35. (do ((ns (range 9) (cdr ns))) ((null? ns))
  36. (display (member? < (car ns) tree)) (newline))
  37.  
  38. (define (enlist tree)
  39. (cond ((null? tree) (list))
  40. ((and (null? (cadr tree)) (null? (caddr tree)))
  41. (list (car tree)))
  42. (else (append (enlist (cadr tree))
  43. (list (car tree))
  44. (enlist (caddr tree))))))
  45.  
  46. (define (nth n tree) (list-ref (enlist tree) n))
  47.  
  48. (display (enlist tree)) (newline)
  49.  
  50. (do ((ns (range 8) (cdr ns))) ((null? ns))
  51. (display (nth (car ns) tree)) (newline))
  52.  
  53. (define (nth n tree)
  54. (call-with-current-continuation
  55. (lambda (return)
  56. (let ((n n))
  57. (let loop ((tree tree))
  58. (when (pair? tree)
  59. (loop (cadr tree))
  60. (when (zero? n)
  61. (return (car tree)))
  62. (set! n (- n 1))
  63. (loop (caddr tree))))
  64. (return #f)))))
  65.  
  66. (do ((ns (range 9) (cdr ns))) ((null? ns))
  67. (display (nth (car ns) tree)) (newline))
Success #stdin #stdout 0.01s 43152KB
stdin
Standard input is empty
stdout
(3 (2 (1 (0 () ()) ()) ()) (5 (4 () ()) (7 (6 () ()) ())))
#t
#t
#t
#t
#t
#t
#t
#t
#f
(0 1 2 3 4 5 6 7)
0
1
2
3
4
5
6
7
0
1
2
3
4
5
6
7
#f