Tuesday, February 21, 2012

Scala saves you lines

Very brief post about Scala programming

Few days ago I played a bit with Scala's fold operations.

I had a list containing rules that all needed to be completed to continue.

Because I have a long history with Java, the first version:
def areRulesCompleted(ruleList:List[Rule]):Boolean= {
var isCompleted:Boolean = true
ruleList.foreach(rule =>{
if (!rule.isCompleted) isCompleted = false
return isCompleted

As you can see there's plenty of rows and it's not very functional. Then with foldLeft
ruleList.foldLeft(true)((resolvedValue,rule)=>(resolvedValue && rule.isCompleted))
Better! But we can do it even simpler way
ruleList.foldLeft(true)(_ && _.isCompleted)

so combining this with the method declaration:
def areRulesCompleted(ruleList:List[Rule]) = ruleList.foldLeft(true)(_ && _.isCompleted)
Here's even shorter version (short-circuit) by: Ilkka.
def areRulesCompleted(rules: List[Rule]) = !rules.exists(!_.isCompleted)
I also checked that foldLeft is short-circuiting but foldRight is not.


  1. Here's a Clojure version that has short-circuit semantics. Maybe there is a Scala equivalent?

    (defn rules-completed? [rules] (every? complete? rules))

  2. Short-circuited version:

    def areRulesCompleted(rules: List[Rule]) = !rules.exists(!_.isCompleted)

    Nice blog by the way!

    1. Thanks for the comment, I added your version to the blog entry. Really nice way to handle it.

  3. There is also the forall method:

    def areRulesCompleted(rules: List[Rule]) = rules.forall(_.isCompleted)