Option.fold() Considered Unreadable
Join the DZone community and get the full member experience.
Join For FreeWe had a lengthy discussion recently during code review whether
scala.Option.fold() is idiomatic and clever or maybe unreadable and tricky? Let's first describe what the problem is. Option.fold does two things: maps a function f overOption's value (if any) or returns an alternative alt if it's absent. Using simple pattern matching we can implement it as follows:val option: Option[T] = //...
def alt: R = //...
def f(in: T): R = //...
val x: R = option match {
case Some(v) => f(v)
case None => alt
}
If you prefer one-liner, fold is actually a combination of map and getOrElseval x: R = option map f getOrElse altOr, if you are a C programmer that still wants to write in C, but using Scala compiler:
val x: R = if (option.isDefined)
f(option.get)
else
alt
Interestingly this is similar to how fold() is actually implemented, but that's an implementation detail. OK, all of the above can be replaced with single Option.fold():val x: R = option.fold(alt)(f)Technically you can even use
/: and \: operators (alt /: option) - but that would be simply masochistic. I have three problems with option.fold() idiom. First of all - it's anything but readable. We are folding (reducing) over Option - which doesn't really make much sense. Secondly it reverses the ordinary positive-then-negative-case flow by starting with failure (absence, alt) condition followed by presence block (f function; see also: Refactoring map-getOrElse to fold). Interestingly this method would work great for me if it was named mapOrElse:**
* Hypothetical in Option
*/
def mapOrElse[B](f: A => B, alt: => B): B =
this map f getOrElse alt
Actually there is already such method in Scalaz, called OptionW.cata. cata. Here is whatMartin Odersky has to say about it:"I personally find methods likecatathat take two closures as arguments are often overdoing it. Do you really gain in readability overmap+getOrElse? Think of a newcomer to your code[...]"Whilecatahas some theoretical background,Option.foldjust sounds like a random name collision that doesn't bring anything to the table, apart from confusion. I know what you'll say, thatTraversableOncehasfoldand we are sort-of doing the same thing. Why it's a random collision rather than extending the contract described inTraversableOnce?fold()method in Scala collections typically just delegates to one offoldLeft()/foldRight()(the one that works better for given data structure), thus it doesn't guarantee order and folding function has to be associative. But inOption.fold()the contract is different: folding function takes just one parameter rather than two. If you read my previous article about folds you know that reducing function always takes two parameters: current element and accumulated value (initial value during first iteration). ButOption.fold()takes just one parameter: currentOptionvalue! This breaks the consistency, especially when realizingOption.foldLeft()andOption.foldRight()have correct contract (but it doesn't mean they are more readable).
The only way to understand folding over option is to imagineOptionas a sequence with0or1elements. Then it sort of makes sense, right? No.
def double(x: Int) = x * 2 Some(21).fold(-1)(double) //OK: 42 None.fold(-1)(double) //OK: -1but:
Some(21).toList.fold(-1)(double) <console>: error: type mismatch; found : Int => Int required: (Int, Int) => Int Some(21).toList.fold(-1)(double) ^If we treatOption[T]as aList[T], awkwardOption.fold()breaks because it has different type thanTraversableOnce.fold(). This is my biggest concern. I can't understand why folding wasn't defined in terms of the type system (trait?) and implemented strictly. As an example take a look at:
Data.Foldablein Haskell (advanced)Data.Foldabletypeclass describes various flavours of folding in Haskell. There are familiarfoldl/foldr/foldl1/foldr1, in Scala namedfoldLeft/foldRight/reduceLeft/reduceRightaccordingly. They have the same type as Scala and behave unsurprisingly with all types that you can fold over, includingMaybe, lists, arrays, etc. There is also a function namedfold, but it has a completely different meaning:
class Foldable t where fold :: Monoid m => t m -> mWhile other folds are quite complex, this one barely takes a foldable container ofms (which have to beMonoids) and returns the sameMonoidtype. A quick recap: a type can be aMonoidif there exists a neutral value of that type and an operation that takes two values and produces just one. Applying that function with one of the arguments being neutral value yields the other argument.String([Char]) is a good example with empty string being neutral value (mempty) and string concatenation being such operation (mappend). Notice that there are two different ways you can construct monoids for numbers: under addition with neutral value being0(x + 0 == 0 + x == xfor anyx) and under multiplication with neutral1(x * 1 == 1 * x == xfor anyx). Let's stick to strings. If I fold empty list of strings, I'll get an empty string. But when a list contains many elements, they are being concatenated:
> fold ([] :: [String]) "" > fold [] :: String "" > fold ["foo", "bar"] "foobar"In the first example we have to explicitly say what is the type of empty list[]. Otherwise Haskell compiler can't figure out what is the type of elements in a list, thus which monoid instance to choose. In second example we declare that whatever is returned fromfold [], it should be aString. From that the compiler infers that[]actually must have a type of[String]. Lastfoldis the simplest: the program folds over elements in list and concatenates them because concatenation is the operation defined inMonoid Stringtypeclass instance.
Back to options (or more preciselyMaybe). Folding overMaybemonad having type parameter beingMonoid(I can't believe I just said it) has an interesting interpretation: it either returns value insideMaybeor a defaultMonoidvalue:
> fold (Just "abc") "abc" > fold Nothing :: String ""Just "abc"is same asSome("abc")in Scala. You can see here that ifMaybe StringisNothing, neutralStringmonoid value is returned, that is an empty string.
Summary
Haskell shows that folding (also overMaybe) can be at least consistent. In ScalaOption.foldis unrelated toList.fold, confusing and unreadable. I advise avoiding it and staying with slightly more verbosemap/getOrElsetransformations or pattern matching.
PS: Did I mention there is alsoEither.fold()(with even different contract) but noTry.fold()?
Strings
Scala (programming language)
Database
Element
Fold (Unix)
Haskell (programming language)
Data Types
Type system
IT
Opinions expressed by DZone contributors are their own.
Comments