jeudi, mars 10, 2011

Scala TreeSet: foreach vs foldLeft

Here is the best article I found to understand what is foldLeft. And here is an example on how to replace foreach with foldLeft:


class KbdKey() {
  def generateQuartets(): ListSet[Quartet] = {...}
}

class KbdMatrix() {
  var ts_keys = new TreeSet[KbdKey]()

  var l_quartets = ListSet.empty[Quartet];
  ts_keys.foreach(l_quartets ++= _.generateQuartets())

  // 2 lines above can be replaced by the line below

  val l_quartets = ts_keys.tail.foldLeft(ts_keys.head.generateQuartets)(_ ++ _.generateQuartets)
}

Aucun commentaire: