Last active
March 24, 2020 11:01
-
-
Save ssanj/c47f99a1aa100e69576539ee5eddf6eb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//I'm trying to implement `intersperse` from : https://fs2.io/guide.html#exercises-stream-transforming | |
import fs2.Stream | |
import fs2.Pipe | |
import fs2.Chunk | |
import fs2.Pull | |
import cats.effect.IO | |
import scala.language.higherKinds | |
object Intersperse { | |
//Stream("Alice","Bob","Carol").intersperse("|").toList | |
//res37: List[String] = List("Alice", "|", "Bob", "|", "Carol") | |
def intersperse[F[_], O](sep: O): Pipe[F, O, O] = { | |
def go(s: Stream[F, O]): Pull[F, O, Unit] = { | |
s.pull.uncons.flatMap { | |
case Some((ch, nextStream)) => | |
ch.toList match { | |
case Nil => go(nextStream) | |
case h :: Nil => Pull.output(Chunk(h)) >> go(nextStream) //this could emit an unbalanced sep | |
case xs => Pull.output(Chunk.seq[O](xs.init.flatMap(x => List(x, sep)) :+ xs.last)) >> go(nextStream) | |
} | |
case None => Pull.done | |
} | |
} | |
in => go(in).stream | |
} |
Another possible implementation for intersperse:
def intersperse2[F[_], O](s1: Stream[F, O], sep: O): Stream[F, O] =
s1.chunks.flatMap(ch => Stream.emits(ch.toVector.flatMap(x => Vector(x, sep))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
But if we do something even:
//we get a trailing '#'.
Questions
intersperse
method to Stream?