Zipper to iterate over list in Scala

早过忘川 提交于 2019-11-30 18:22:45

One of the many neat things about zippers is that they have a comonad instance, which allows us to solve a certain class of problems very elegantly.

Here's a quick example off the top of my head. Suppose that we've got a sequence of numbers and we want to do a simple form of smoothing with an exponential moving average, where the new value for each position in the list is an average of the current value and all the other values, but with more distant neighbors contributing less.

This isn't a terribly hard thing to compute imperatively, but if we use a zipper and a comonadic cobind it's not too far from a one-liner:

import scalaz._, Scalaz._

val weights = Stream.from(1).map(1.0 / math.pow(2, _))

def sumNeighborWeights(neighbors: Stream[Double]) =
  neighbors.fzipWith(weights)(_ * _).sum

def smooth(data: NonEmptyList[Double]) = data.toZipper.cobind { z =>
  (z.focus + sumNeighborWeights(z.lefts) + sumNeighborWeights(z.rights)) / 3
}

Now if we write:

val result = smooth(NonEmptyList[Double](0, 0, 0, 1, 0, 0, 0)).toList

We'll get the moral equivalent of:

List(1 / 24, 1 / 12, 1 / 6, 1 / 3, 1 / 6, 1 / 12, 1 / 24)

Which is what we want, given how we defined the problem.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!