如果要找到ZIO Stream的大小,我有两个流,想找到两者之间的内积,我的问题是如何找到大小以便迭代它们。我使用map和foldMap解决了这个问题,但我想检查两种方法之间的性能?这是我使用折叠和地图的作品:
import zio._
import zio.console.{Console, putStrLn}
import zio.stream._
object InnerProduct extends App {
val stream1: Stream[Nothing, Int] = Stream(1,2,3,4)
val stream2: Stream[Nothing, Int] = Stream(4,5,6,7)
def inner_fold [A,B,C,D,E](stream1:Stream[Nothing,A])(stream2:Stream[Nothing,B])(tms: (A, B) => C)(pls: (D, C) => D)(zero: D)= for{
acc <- Ref.make(zero)
acc2 <- acc.get
i = 0
compStream = stream1.zip(stream2)
str = compStream.map(i => tms(i._1,i._2))
streamFold<- str.fold(acc2)(pls)
_ <-acc.set(streamFold)
} yield acc
override def run(args: List[String]) =
for {
res <- inner_fold[Int, Int, Int, Int,Int](stream1)(stream2)(_ * _)(_ + _ )(0)
res2 <-res.get
_ <- putStrLn(res2.toString)
} yield (0)
}
输出:60
我假设,通过"内积",您的意思是有两个Stream[Double]
,您希望将其视为数学向量,并在迭代整个流后计算单个输出值。
为此,很容易使用zip
来计算两个流的元素乘积,然后使用foldLeft
来计算最终结果。
val products: Stream[Double] = stream1.zip(stream2).map(_ * _)
val innerProduct: UIO[Double] = products.run(Sink.foldLeft(_ * _))