Back to Fpinscala

06.Answer

answerkey/streamingio/06.answer.md

latest696 B
Original Source
scala
def countViaMapAccumulate: Pull[Int, R] =
  Output(0) >> mapAccumulate(0)((s, o) => (s + 1, s + 1)).map(_(1))

def tallyViaMapAccumulate[O2 >: O](using m: Monoid[O2]): Pull[O2, R] =
  Output(m.empty) >> mapAccumulate(m.empty): (s, o) =>
    val s2 = m.combine(s, o)
    (s2, s2)
  .map(_(1))

extension [R](self: Pull[Int, R])
  def slidingMeanViaMapAccumulate(n: Int): Pull[Double, R] =
    self.mapAccumulate(Queue.empty[Int]): (window, o) =>
      val newWindow = if window.size < n then window :+ o
                                         else window.tail :+ o
      val meanOfNewWindow = newWindow.sum / newWindow.size.toDouble
      (newWindow, meanOfNewWindow)
    .map(_(1))