vector-procs.scm 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. (library (vector-procs)
  2. (export vector-filter)
  3. (import (rnrs base)
  4. (only (guile)
  5. lambda* λ)
  6. ;; SRFIs
  7. ;; srfi-43 for vector procs
  8. (srfi srfi-43)))
  9. (define vector-copy-elements!
  10. (λ (source target indices)
  11. "Copy elements from vector SOURCE at INDICES to vector TARGET."
  12. ;; Iteratively copy all elements, which are matching.
  13. (let iter ([remaining-indices indices]
  14. [target-next-ind 0])
  15. (cond
  16. ;; If no more indices are left, return the new vector.
  17. [(null? remaining-indices) target]
  18. [else
  19. ;; Copy over the value from the source vector.
  20. (vector-set! target
  21. target-next-ind
  22. (vector-ref source (car remaining-indices)))
  23. ;; Continue with the rest of the indices.
  24. (iter (cdr remaining-indices)
  25. (+ target-next-ind 1))]))))
  26. (define vector-filter
  27. (λ (pred vec)
  28. "Filter a vector and return the filtered vector."
  29. (define iter
  30. (λ (index entries-found-count indices)
  31. "Iterate over the whole vector from last to first
  32. element, keeping track of elements, for which the predicate
  33. pred is true. Build a list in reverse, which will be in the
  34. order of going from first to last element of the vector,
  35. without the need to reverse it later."
  36. (cond
  37. ;; If the whole vector has been searched for
  38. ;; matching elements, return the indices of
  39. ;; matching elements and the number of matching
  40. ;; elements found.
  41. [(< index 0)
  42. (values indices entries-found-count)]
  43. ;; Otherwise continue iterating over the vector.
  44. [else
  45. (let ([vec-elem (vector-ref vec index)])
  46. (cond
  47. ;; Case for matching elements.
  48. [(pred vec-elem)
  49. (iter (- index 1)
  50. (+ entries-found-count 1)
  51. (cons index indices))]
  52. [else
  53. (iter (- index 1)
  54. entries-found-count
  55. indices)]))])))
  56. (let-values ([(indices entries-found-count)
  57. (iter (- (vector-length vec) 1)
  58. 0
  59. '())])
  60. (vector-copy-elements! vec
  61. (make-vector entries-found-count
  62. 'undefined)
  63. indices))))