list-procs.scm 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. (library (lib list-procs)
  2. (export rest
  3. range
  4. enumerate
  5. flatten
  6. filter*)
  7. (import
  8. (except (rnrs base) let-values map error)
  9. (only (guile)
  10. ;; lambda forms
  11. lambda* λ
  12. ;; conditionals
  13. when
  14. ;; input output
  15. simple-format
  16. current-output-port
  17. call-with-output-string
  18. current-input-port
  19. ;; strings
  20. string-trim
  21. string-join
  22. string-append
  23. string-delete
  24. ;; other
  25. error)
  26. ;; srfi-1 for list procedures
  27. (srfi srfi-1)
  28. (lib string-procs)
  29. (prefix (lib logger) log:)))
  30. (define rest cdr)
  31. (define range
  32. (lambda* (start end #:key (end-inclusive #f) (start-inclusive #t) (step 1))
  33. (cond
  34. [(> start end) '()]
  35. [(= start end)
  36. (cond [end-inclusive (cons end '())]
  37. [else '()])]
  38. [else
  39. (cond [start-inclusive
  40. (cons start
  41. (range (+ start step)
  42. end
  43. #:end-inclusive end-inclusive
  44. #:step step))]
  45. [else
  46. (range (+ start step)
  47. end
  48. #:end-inclusive end-inclusive
  49. #:start-inclusive #t ; change after first element
  50. #:step step)])])))
  51. (define flatten
  52. (λ (lst)
  53. (cond [(null? lst) '()]
  54. [(pair? lst)
  55. (append (flatten (car lst))
  56. (flatten (cdr lst)))]
  57. [else
  58. (list lst)])))
  59. (define filter*
  60. (λ (pred lst-or-atom)
  61. (log:debug (string-format "remaining lst-or-atom: ~a" lst-or-atom))
  62. (cond
  63. [(null? lst-or-atom) '()]
  64. [(pair? lst-or-atom)
  65. (cond
  66. [(pair? (car lst-or-atom))
  67. (cons (filter* pred (car lst-or-atom))
  68. (filter* pred (cdr lst-or-atom)))]
  69. [else
  70. (cond
  71. [(pred (car lst-or-atom))
  72. (cons (car lst-or-atom)
  73. (filter* pred (cdr lst-or-atom)))]
  74. [else
  75. (filter* pred (cdr lst-or-atom))])])]
  76. [(pred lst-or-atom) lst-or-atom]
  77. [else '()])))
  78. (define enumerate
  79. (lambda* (lst #:key (start 0) (step 1))
  80. (range start (length lst) #:step 1)))