peg-tree-utils.scm 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. (library (peg-tree-utils)
  2. (export find-in-peg-tree
  3. find-all-in-peg-tree
  4. flatten-filter-peg-tree)
  5. (import
  6. (except (rnrs base) let-values)
  7. (only (guile)
  8. lambda* λ
  9. error)
  10. (prefix (logging) log:)
  11. (prefix (srfi srfi-1) srfi-1:)))
  12. (define rest cdr)
  13. (define find-in-peg-tree
  14. (lambda* (peg-tree label #:key (label-equal? symbol=?))
  15. (cond
  16. [(null? peg-tree) #f]
  17. [(pair? (srfi-1:first peg-tree))
  18. (or (find-in-peg-tree (srfi-1:first peg-tree)
  19. label
  20. #:label-equal? label-equal?)
  21. (find-in-peg-tree (rest peg-tree)
  22. label
  23. #:label-equal? label-equal?))]
  24. [(label-equal? (srfi-1:first peg-tree) label)
  25. ;;(cadadr peg-tree)
  26. peg-tree]
  27. [else
  28. (find-in-peg-tree (rest peg-tree)
  29. label
  30. #:label-equal? label-equal?)])))
  31. (define find-all-in-peg-tree
  32. (lambda* (peg-tree label #:key (label-equal? symbol=?))
  33. (cond
  34. [(null? peg-tree) '()]
  35. [(pair? (srfi-1:first peg-tree))
  36. (cons (find-all-in-peg-tree (srfi-1:first peg-tree)
  37. label
  38. #:label-equal? label-equal?)
  39. (find-all-in-peg-tree (rest peg-tree)
  40. label
  41. #:label-equal? label-equal?))]
  42. ;; found a match
  43. [(label-equal? (srfi-1:first peg-tree) label)
  44. peg-tree]
  45. [else
  46. (find-all-in-peg-tree (rest peg-tree)
  47. label
  48. #:label-equal? label-equal?)])))
  49. (define flatten-filter-peg-tree
  50. (lambda* (peg-tree label #:key (label-equal? symbol=?))
  51. (cond
  52. [(null? peg-tree) '()]
  53. ;; if nested list
  54. [(pair? (srfi-1:first peg-tree))
  55. ;; The first element is at least a pair and the rest is also either a pair
  56. ;; or null: ((?) ?)
  57. (cond
  58. ;; Check, if the car of the list is the structure we are looking for,
  59. ;; take it and append the results from the rest of the peg tree.
  60. [(label-equal? (srfi-1:first (srfi-1:first peg-tree))
  61. label)
  62. (append (list (srfi-1:first peg-tree))
  63. (flatten-filter-peg-tree (rest peg-tree)
  64. label
  65. #:label-equal? label-equal?))]
  66. [else
  67. ;; If the car of the list is not the structure we are looking for,
  68. ;; search in it and in the rest of the list.
  69. (append (flatten-filter-peg-tree (srfi-1:first peg-tree)
  70. label
  71. #:label-equal? label-equal?)
  72. (flatten-filter-peg-tree (rest peg-tree)
  73. label
  74. #:label-equal? label-equal?))])]
  75. [else
  76. ;; If the searched element is not the first element, then search the rest
  77. ;; of the tree.
  78. (flatten-filter-peg-tree (rest peg-tree)
  79. label
  80. #:label-equal? label-equal?)])))