list-helpers.scm 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. (library (list-helpers)
  2. (export flatten
  3. make-list
  4. split-off-n
  5. split-into-n-sized-segments
  6. split-at
  7. split-into-segments)
  8. (import
  9. (except (rnrs base) let-values map error)
  10. (only (guile)
  11. lambda* λ)
  12. ;; receive form
  13. (srfi srfi-8))
  14. (define flatten
  15. (λ (lst)
  16. (cond [(null? lst) '()]
  17. [(pair? lst)
  18. (append (flatten (car lst))
  19. (flatten (cdr lst)))]
  20. [else
  21. (list lst)])))
  22. (define make-list
  23. (λ (val count)
  24. (cond
  25. [(> count 0)
  26. (cons val (make-list val (- count 1)))]
  27. [else '()])))
  28. (define split-off-n
  29. (λ (lst n)
  30. (let iter ([lst° lst]
  31. [counter 0]
  32. [cont
  33. (λ (acc-split-off rem-lst)
  34. (values acc-split-off rem-lst))])
  35. (cond
  36. [(null? lst°)
  37. (cont '() lst°)]
  38. [(= counter n)
  39. (cont '() lst°)]
  40. [else
  41. (iter (cdr lst°)
  42. (+ counter 1)
  43. (λ (new-tail rem-lst)
  44. (cont (cons (car lst°) new-tail)
  45. rem-lst)))]))))
  46. (define split-into-n-sized-segments
  47. (λ (lst n)
  48. (cond
  49. [(null? lst) '()]
  50. [else
  51. (receive (split-off-part remaining-list)
  52. (split-off-n lst n)
  53. (cons split-off-part
  54. (split-into-n-sized-segments remaining-list n)))])))
  55. (define split-at
  56. (λ (lst pred)
  57. (let iter ([lst° lst]
  58. [cont
  59. (λ (acc-split-off rem-lst)
  60. (values acc-split-off rem-lst))])
  61. (cond
  62. [(null? lst°)
  63. (cont '() lst°)]
  64. [(pred (car lst°))
  65. (cont '() (cdr lst°))]
  66. [else
  67. (iter (cdr lst°)
  68. (λ (new-tail rem-lst)
  69. (cont (cons (car lst°) new-tail)
  70. rem-lst)))]))))
  71. (define split-into-segments
  72. (λ (lst pred)
  73. (cond
  74. [(null? lst) '()]
  75. [else
  76. (receive (split-off-part remaining-list) (split-at lst pred)
  77. (cons split-off-part
  78. (split-into-segments remaining-list pred)))]))))