Hacker News new | past | comments | ask | show | jobs | submit login

Fold is incredibly important. You should learn it. https://en.wikipedia.org/wiki/Fold_(higher-order_function)

In Scala, the debate between using fold on an Option or using map and getOrElse is almost as old as the language. The method signature for this is:

  def fold[B](ifEmpty: => B)(f: (A) => B): B
That is to say, fold always returns type B, and takes two arguments. The first takes a function returning type B if the option is "empty" (None) and the second takes a function that is called with the contents of the Some. As you can see, it's syntactic sugar for map and getOrElse.

  def map[B](f: (A) => B): B

  def getOrElse[B](f: => B): B



If it's syntactic sugar for map and getOrElse what is really gained? If the definition of fold is mapAndGetOrElse why add an additional concept to burden programmers minds with? GetOrElse is independently useful and everyone needs to know map anyway. Using fold just seems like a lost opportunity to teach someone getOrElse with no real benefit.

You make the Understanding This Codebase 101 curriculum some percent longer without making your programmers any better.

If it's terseness, I don't really think one symbol is any verbosity benefit over two. Same order of magnitude, same cost. It's a rounding error in brevity. People way overvalue terseness.

And the cost of people missing chances to learn getOrElse has got to be massive.


I haven't used Scala for years, but fold[0] is one of the functional programming building blocks. It's applicable across languages and data types.

It looks like syntactic sugar here, but it's really not. It's just a function that is more commonly used on collections with more than one item.

[0] also reduce, inject, aggregate, and other synonyms, because naming is hard


map and getOrElse are syntactic sugar for fold, not the other way around.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: