peg-tree-utils.scm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (library (peg-tree-utils)
  2. (export find-in-tree
  3. find-in-tree*)
  4. (import
  5. (except (rnrs base) let-values)
  6. (only (guile) lambda* λ
  7. current-output-port
  8. simple-format)
  9. (srfi srfi-1)))
  10. (define find-in-tree
  11. (λ (peg-tree label equal-test)
  12. (define traverse
  13. (λ (peg-tree label)
  14. (cond
  15. [(null? peg-tree) #f]
  16. [(pair? (car peg-tree))
  17. (or (traverse (first peg-tree) label)
  18. (traverse (cdr peg-tree) label))]
  19. [(symbol? (car peg-tree))
  20. (cond
  21. [(equal-test (car peg-tree) label)
  22. (cdr peg-tree)]
  23. [else
  24. (traverse (cdr peg-tree) label)])]
  25. [else
  26. (traverse (cdr peg-tree) label)])))
  27. (traverse peg-tree label)))
  28. (define find-in-tree*
  29. (λ (peg-tree filter-proc)
  30. (define traverse
  31. (λ (subtree cont)
  32. ;; (simple-format (current-output-port)
  33. ;; "working with subtree ~a\n"
  34. ;; subtree)
  35. (cond
  36. [(null? subtree) (cont)]
  37. [(pair? (first subtree))
  38. (traverse (first subtree)
  39. (λ () (traverse (cdr subtree) cont)))]
  40. [(filter-proc (first subtree))
  41. (cons subtree (cont))]
  42. [else
  43. (traverse (cdr subtree) cont)])))
  44. (traverse peg-tree (λ () '()))))
  45. ;; An alternative version, not using continuations,
  46. ;; submitted by Taylan Kammen on the Guile User mailing list
  47. ;; is the following:
  48. ;; (define find-in-tree*
  49. ;; (λ (peg-tree filter-proc)
  50. ;; (define traverse
  51. ;; (λ (subtree rest)
  52. ;; (simple-format (current-output-port) "working with subtree ~a\n" subtree)
  53. ;; (cond
  54. ;; [(null? subtree)
  55. ;; (if (null? rest)
  56. ;; '()
  57. ;; (traverse (car rest) (cdr rest)))]
  58. ;; [(pair? (first subtree))
  59. ;; (traverse (first subtree)
  60. ;; (cons (cdr subtree) rest))]
  61. ;; [(filter-proc (first subtree))
  62. ;; (cons subtree
  63. ;; (if (null? rest)
  64. ;; '()
  65. ;; (traverse (car rest) (cdr rest))))]
  66. ;; [else
  67. ;; (traverse (cdr subtree) rest)])))
  68. ;; (traverse peg-tree '())))