Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Created December 10, 2011 05:54
Show Gist options
  • Save mumoshu/1454670 to your computer and use it in GitHub Desktop.
Save mumoshu/1454670 to your computer and use it in GitHub Desktop.
Various accumulation examples in Scala
/** まず、import, case class, val nodeseqのところまで
* REPLの:pasteコマンドでコピペして、各Exampleも同様にコピペして実行してみてね!
*
* Use :paste command in Scala REPL to run example code.
*/
import xml._
case class ColorPair(foregroundOption: Option[String], backgroundOption: Option[String])
/** テストデータ
* Foreground, Backgroundのvalueだけを抽出してColorPairをつくりたい。
*
* Test data
* I want to extract and compose values of nodes named "Foreground" and "Background" to build a ColorPair
*/
val nodeseq = NodeSeq.fromSeq(Seq(
<option name="Foreground" value="586e75"></option>,
<option name="NoValue"></option>,
<option name="Background" value="4d1d08"></option>,
<option name="Irrelevant" value="123456"></option>
))
/** 期待結果
* Expected result
*/
ColorPair(Some(586e75),Some(4d1d08))
# Example 1. Accumulation (foldLeft + match)
nodeseq.view
.map(node => (node.attribute("name").map(_.text), node.attribute("value").map(_.text)))
.foldLeft(ColorPair(None, None)) { (cp, t) => t._1 match {
case Some("Foreground") => ColorPair(t._2, cp.backgroundOption)
case Some("Background") => ColorPair(cp.foregroundOption, t._2)
case _ => cp
}
}
// res1: ColorPair = ColorPair(Some(586e75),Some(4d1d08))
# Example 2. Accumulation (foldLeft + partial function)
nodeseq.view
.map(node => (node.attribute("name").map(_.text), node.attribute("value").map(_.text)))
.foldLeft(ColorPair(None, None)) {
case (cp, (Some("Foreground"), foregroundOption)) => ColorPair(foregroundOption, cp.backgroundOption)
case (cp, (Some("Background"), backgroundOption)) => ColorPair(cp.foregroundOption, backgroundOption)
case (cp, _) => cp
}
// res2: ColorPair = ColorPair(Some(586e75),Some(4d1d08))
# Example 3. Use temporary vals 1 (collectFirst)
val nameValuePairs = nodeseq.view
.map(node => (node.attribute("name").map(_.text), node.attribute("value").map(_.text)) )
val foregroundOption = nameValuePairs.collectFirst {
case (Some("Foreground"), Some(foreground)) => foreground
}
val backgroundOption = nameValuePairs.collectFirst {
case (Some("Background"), Some(background)) => background
}
ColorPair(foregroundOption, backgroundOption)
// res3: ColorPair = ColorPair(Some(586e75),Some(4d1d08))
# Example 4. Use temporary vals 2 (find + flatMap)
val nameValuePairs = nodeseq.view
.map(node => (node.attribute("name").map(_.text), node.attribute("value").map(_.text)) )
val foregroundOption = nameValuePairs.find(_._1 == Some("Foreground")).flatMap(_._2)
val backgroundOption = nameValuePairs.find(_._1 == Some("Background")).flatMap(_._2)
ColorPair(foregroundOption, backgroundOption)
// res4: ColorPair = ColorPair(Some(586e75),Some(4d1d08))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment