background preloader

Collections

Facebook Twitter

Scala.collection.immutable.List. Lots And Lots Of foldLeft Examples « Matt Malone’s Old-Fashioned Software Development Blog. In my last post I reviewed the implementation of scala.List’s foldLeft and foldRight methods. That post included a couple of simple examples, but today I’d like to give you a whole lot more. The foldLeft method is extremely versatile. It can do thousands of jobs. Of course, it’s not the best tool for EVERY job, but when working on a list problem it’s a good idea to stop and think, “Should I be using foldLeft?”

Below, I’ll present a list of problem descriptions and solutions. Sum Write a function called ‘sum’ which takes a List[Int] and returns the sum of the Ints in the list. I’ll explain this first example in a bit more depth than the others, just to make sure we all know how foldLeft works. These two definitions above are equivalent. The foldLeft method takes that initial value, 0, and the function literal, and it begins to apply the function on each member of the list (parameter ‘c’), updating the result value (parameter ‘r’) each time. Product Did you get it? Count Average Last Whew! Get. Scala 2.8 Collections API ← Decodified. Scala 2.8 collections design tutorial. Scala 2.8 Collections API. Scala.collection.immutable.TreeSet.