Skip to content

Instantly share code, notes, and snippets.

@justinhj
Created April 9, 2018 16:26
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 justinhj/b1ef60cd41e373fd0c947e87875f3b26 to your computer and use it in GitHub Desktop.
Save justinhj/b1ef60cd41e373fd0c947e87875f3b26 to your computer and use it in GitHub Desktop.
FS2 gist to pull from a stream until N items that return true for the provided predicate
def takeWhileRepeat[F[_],O](n: Long, f: O => Boolean): Pipe[F,O,O] = {
def go(s: Stream[F,O], wasTrueCount : Int) : Pull[F,O,Unit] = {
if(wasTrueCount == n) {
Pull.done
}
else {
s.pull.uncons1.flatMap {
case Some((o, tl)) =>
if(f(o)) {
Pull.output1(o) >> go(tl, wasTrueCount + 1)
}
else {
Pull.output1(o) >> go(tl, wasTrueCount)
}
case None =>
Pull.done
}
}
}
in => go(in, 0).stream
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment