0

I have a Stream[A] and a function zeroOrMoreB(value: A): Seq[B] which given an A returns zero or more B. From these two pieces, how to I construct a Stream[B]?

I can get a Stream[Stream[B]] (see below), but I cannot figure out how to flatten it.

stream <- ZStream
  .fromIterable(vectorOfAs)
  .map(zeroOrMoreB)
RandomBits
  • 4,194
  • 1
  • 17
  • 30

2 Answers2

3

As I always say, the Scaladoc is your friend.

You can use mapConcat

val stream = ZStream.fromIterable(vectorOfAs).mapConcat(zeroOrMoreB)

Now if zeroOrMoreB actually returns a ZStream instead of a Seq, you just use flatMap

val stream = ZStream.fromIterable(vectorOfAs).flatMap(zeroOrMoreB)

Finally, if you like for syntax you can do this

val stream = for {
  a <- ZStream.fromIterable(vectorOfAs)
  b <- ZStream.fromIterable(zeroOrMoreB(a))
} yield b
0

I was clearly not thinking straight -- .flatMap does the trick.

stream <- ZStream
  .fromIterable(vectorOfAs)
  .flatMap(a => zeroOrMoreB(a))
RandomBits
  • 4,194
  • 1
  • 17
  • 30