Last active
December 16, 2020 13:48
-
-
Save ruliana/361a50f1fbcdda248577a6ba3cf2a880 to your computer and use it in GitHub Desktop.
Consecutive sequences of elements matching a predicate in Racket (lazy-version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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