Skip to content

Instantly share code, notes, and snippets.

@ruliana
Last active December 16, 2020 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruliana/361a50f1fbcdda248577a6ba3cf2a880 to your computer and use it in GitHub Desktop.
Save ruliana/361a50f1fbcdda248577a6ba3cf2a880 to your computer and use it in GitHub Desktop.
Consecutive sequences of elements matching a predicate in Racket (lazy-version)
#lang racket
(define (in-groups keep? seq)
(let loop ([rem seq] ;; Remaining elements.
[group empty]) ;; Accumulates the sequence until we spit it.
(cond [(empty? rem)
(if (empty? group) ;; When hit the end condition, check if there
empty-stream ;; is something to spit.
group)]
[(keep? (first rem)) ;; Keep the element? Add to group.
(loop (rest rem) (cons (first rem) group))]
[(empty? group) ;; Not keep and empty group? Just continue.
(loop (rest rem) group)]
[else ;; Not keep and something to spit?
(stream-cons group (loop (rest rem) empty))]))) ;; Lazy recurse!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment