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.
Here's a Clojure version that has short-circuit semantics. Maybe there is a Scala equivalent?
ReplyDelete(defn rules-completed? [rules] (every? complete? rules))
Short-circuited version:
ReplyDeletedef areRulesCompleted(rules: List[Rule]) = !rules.exists(!_.isCompleted)
Nice blog by the way!
Thanks for the comment, I added your version to the blog entry. Really nice way to handle it.
DeleteThere is also the forall method:
ReplyDeletedef areRulesCompleted(rules: List[Rule]) = rules.forall(_.isCompleted)