Skip to content

Instantly share code, notes, and snippets.

@Daenyth
Last active December 18, 2018 14:11
Show Gist options
  • Save Daenyth/8f0bcabf8f63bb91f6deb57e2575bbe5 to your computer and use it in GitHub Desktop.
Save Daenyth/8f0bcabf8f63bb91f6deb57e2575bbe5 to your computer and use it in GitHub Desktop.
fs2 Stream / pure stream implemented with impurity

Fold a String stream using StringBuilder instead of Monoid[String], because the monoid performs repeated concatenation.

@ def foldString[F[_]](src: Stream[F, String]): Stream[F, String] = src.fold(new StringBuilder)(_ append _).map(_.result)
defined function foldString

@ val s = foldString(Stream("Hello", " World!"))
s: Stream[Pure, String] = Stream(..)

@ s.toList
res7: List[String] = List("Hello World!")

@ s.toList
res8: List[String] = List("Hello World!Hello World!")

Oops.

Now with Stream.suspend

@ def foldStringFixed[F[_]](src: Stream[F, String]): Stream[F, String] = Stream.suspend(src.fold(new StringBuilder)(_ append _).map(_.result))
defined function foldStringFixed

@ val s = foldStringFixed(Stream("Hello", " World!"))
s: Stream[Pure, String] = Stream(..)

@ s.toList
res11: List[String] = List("Hello World!")

@ s.toList
res12: List[String] = List("Hello World!")

Credit to @mpilquist for the example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment