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