Skip to content

Instantly share code, notes, and snippets.

@blueskyarea
Last active August 29, 2015 14:27
Show Gist options
  • Save blueskyarea/1c6a9f9cb66977046c18 to your computer and use it in GitHub Desktop.
Save blueskyarea/1c6a9f9cb66977046c18 to your computer and use it in GitHub Desktop.
scala sample
object CollectionMethods {
def main(args: Array[String]): Unit = {
val intList = List(1, 2, 3)
val intList2 = List(Set(1, 2), Set(3, 4), Set(5, 6))
val strList = List("Pink", "Blue", "Yellow")
val mixList = List((1, "Pink"), (2, "Blue"), (3, "Yellow"))
// foreach
val listA = intList.foreach(f => f * 2)
println("listA= " + listA)
strList.foreach(f => println(f))
// map
val listB = intList.map(f => f * 2)
println("listB= " + listB)
// collect
val listC = intList.collect{
case 1 => "one"
case 3 => "three"
}
println("listC= " + listC)
// flatten
val listD = intList2.flatten
println("listD= " + listD)
// unzip
val listE = mixList.unzip
println("listE= " + listE)
// zip
val listF = intList zip strList
println("listF= " + listF)
// zipWithIndex
val listG = strList.zipWithIndex
println("listG= " + listG)
// sorted
val listH = List(2, 4, 1, 3).sorted
println("listH= " + listH)
// reverse
val listI = List(2, 4, 1, 3).reverse
println("listI= " + listI)
}
}
object PartialFunction extends App {
def matchFunc01: PartialFunction[String, Option[String]] = {
case "しろ" => Some("ねっけつ")
case "あお" => Some("はなぞの")
}
def matchFunc02: PartialFunction[String, Option[String]] = {
case "ちゃ" => Some("れいほう")
case "みどり" => Some("れんごう")
case _ => None
}
// 01 と 02 を合体した関数
def matchFunc03 = matchFunc01 orElse matchFunc02
println(matchFunc01("しろ"))
println(matchFunc02("みどり"))
println(matchFunc03("ちゃ"))
println(matchFunc03("むらさき"))
println(matchFunc01("ちゃ")) // エラーになる
}
object NekketuSchool extends App {
// 普通の関数
def belongSchool(name: String, schoolName: String): String = {
name + "は、" + schoolName + "高校の生徒だ!"
}
println(belongSchool("くにお", "熱血"))
println(belongSchool("りき", "花園"))
// 関数の部分適用
val belongSchoolNekketu = belongSchool(_: String, "熱血")
val belongSchoolHanazono = belongSchool(_: String, "花園")
val belongSchoolReihou = belongSchool(_: String, "冷峰")
println(belongSchoolNekketu("すがた"))
println(belongSchoolHanazono("さおとめ"))
println(belongSchoolReihou("りゅういち"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment