This is a follow-up to my previous question. I can use an iterator, fold
, zip
, foreach
and others to iterate over a list in Scala. Now I wonder if there are use cases where Zipper
is most appropriate. Suppose I need read-only access without concurrency.
Could you give such an example and explain why the Zipper
is the best choice?
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:
Now if we write:
We'll get the moral equivalent of:
Which is what we want, given how we defined the problem.