scala 構文3

関数オブジェクト

object MyApp{

  def multi(a: Int, b: Int) = a * b
  val multFunc = (_: Int) * (_: Int)

  def main(args: Array[String]): Unit = {
    println(multFunc(3, 5))
  }

}

関数のカリー化

object MyApp {

  def main(args: Array[String]): Unit = {
    // 関数のカリー化
    val multFunc = (a: Int, b: Int) => a * b
    val multFuncCurried = (a: Int) => ((b: Int) => a * b)

    // println(multFunc(3, 5))
    // println(multFuncCurried(3)(5))

    val double = multFuncCurried(2)
    val tripple = multFuncCurried(3)

    println(double(5)) // 10
    println(tripple(5)) // 15
  }

}

関数の部分適用

object MyApp {

  def msg(from: String, to: String, text: String) = s"($from -> $to): $text"

  def main(args: Array[String]): Unit = {

  val msgToKouda = msg(_: String, "Kouda", _:String)
  println(msgToKouda("yamagata", "OK!"))
  println(msgToKouda("yoshimoto", "Great"))
  println(msgToKouda("eto", "good"))

  }

}

タプル

object MyApp {

  def swap(a: Int, b: Int) = (b, a)

  def main(args: Array[String]): Unit = {
  // val data = (12, "igarashi", 52.6)
  // println(data._1)
  // println(data._2)
  // println(data._3)
  val (x, y) = swap(32, 55)
  print(x)
  print(y)
  }

}

List

object MyApp {

  def main(args: Array[String]): Unit = {
    // val scores = List(200, 300, 400)
    val scores = 200 :: 300 :: 400 :: Nil
   println(scores.length)
   println(scores.isEmpty)
   println(scores.tail)
   println(scores.head)
   println(scores(1))
  }

}

set

object MyApp {

  def main(args: Array[String]): Unit = {
    //val answers = Set(5, 3, 4, 5)
    //println(answers)
    // println(answers.container(3))
    //println(answers(3))

    val set1 = Set(1, 3, 5, 8)
    val set2 = Set(3, 5, 7, 9)

    println(set1 & set2)
    println(set1 | set2)
    println(set1 &~ set2)

  }

}

map

object MyApp {

  def main(args: Array[String]): Unit = {

   val sales = Map("yoshida" -> 200, "kimura" -> 500)
   println(sales("yoshida"))
   println(sales("kimura"))
   println(sales.contains("murata"))

  }

}

mutable

    val scores = scala.collection.mutable.Map("ito" -> 55, "yamamoto" -> 65)
   scores("ito") = 60

map, filter, foreach

object MyApp {

  def main(args: Array[String]): Unit = {
    val prices = List(52.3, 48.6, 32.8)

    prices.map(_ * 1.08).filter(_ > 50).foreach(println)

  }

}