Scalaz provides a method named fold
for various ADTs such as Boolean
, Option[_]
, Validation[_, _]
, Either[_, _]
etc. This method basically takes functions corresponding to all possible cases for that given ADT. In other words, a pattern match shown below:
x match {
case Case1(a, b, c) => f(a, b, c)
case Case2(a, b) => g(a, b)
.
.
case CaseN => z
}
is equivalent to:
x.fold(f, g, ..., z)
Some examples:
scala> (9 == 8).fold("foo", "bar")
res0: java.lang.String = bar
scala> 5.some.fold(2 *, 2)
res1: Int = 10
scala> 5.left[String].fold(2 +, "[" +)
res2: Any = 7
scala> 5.fail[String].fold(2 +, "[" +)
res6: Any = 7
At the same time, there is an operation with the same name for the Traversable[_]
types, which traverses over the collection performing certain operation on its elements, and accumulating the result value. For example,
scala> List(2, 90, 11).foldLeft("Contents: ")(_ + _.toString + " ")
res9: java.lang.String = "Contents: 2 90 11 "
scala> List(2, 90, 11).fold(0)(_ + _)
res10: Int = 103
scala> List(2, 90, 11).fold(1)(_ * _)
res11: Int = 1980
Why are these two operations identified with the same name - fold
/catamorphism? I fail to see any similarities/relation between the two. What am I missing?
I think the problem you are having is that you see these things based on their implementation, not their types. Consider this simple representation of types:
Now, let's consider
Option
's fold:So, on
Option
, it reduces every possible case to some value inB
, and return that. Now, let's see the same thing forList
:Note, however, that we have a recursive call there, on
List[A]
. We have to fold that somehow, but we knowfold[B]
on aList[A]
will always returnB
, so we can rewrite it like this:In other words, we replaced
List[A]
byB
, because folding it will always return aB
, given the type signature offold
. Now, let's see Scala's (use case) type signature forfoldRight
:Say, does that remind you of something?
If you think of "folding" as "condensing all the values in a container through an operation, with a seed value", and you think of an Option as a container that can can have at most one value, then this starts to make sense.
In fact,
foldLeft
has the same signature and gives you exactly the same results if you use it on an empty list vs None, and on a list with only one element vs Some:fold
is also defined on bothList
andOption
in the Scala standard library, with the same signature (I believe they both inherit it from a trait, in fact). And again, you get the same results on a singleton list as on Some:I'm not 100% sure about the
fold
from Scalaz onOption
/Either
/etc, you raise a good point there. It seems to have quite a different signature and operation from the "folding" I'm used to.