Scala Learning(2):map,flatMap,filterとFor式

4824 ワード

Collectionsで最も一般的な3つの操作map,flatMap,filter,For式との関係について述べる.
List対の3つの方法の実現
mapのListでの実装:
abstract class List[+T] {
  def map[U](f: T => U): List[U] = this match {
    case x :: xs => f(x) :: xs.map(f)
    case Nil => Nil
  }
}

flatMapのListでの実装:
abstract class List[+T] {
  def flatMap[U](f: T => List[U]): List[U] = this match {
    case x :: xs => f(x) ++ xs.flatMap(f)
    case Nil => Nil
  }
}

フィルタのリストでの実装:
abstract class List[+T] {
  def filter(p: T => Boolean): List[T] = this match {
    case x :: xs =>
      if (p(x)) x :: xs.filter(p) else xs.filter(p)
    case Nil => Nil
  }
}

Form式
次の論理はforで簡単に表現できます.
(1 until n) flatMap (i =>
  (1 until i) filter (j => isPrime(i + j)) map
    (j => (i, j)))
for {
  i <- 1 until n
  j <- 1 until i
  if isPrime(i + j)
} yield (i, j)

forとmap
for (x <- e1) yield e2

// translated to
e1.map(x => e2)

forとfilter
for (x <- e1 if f; s) yield e2

// translated to
for (x <- e1.withFilter(x => f); s) yield e2

forとflatMap
for (x <- e1; y <- e2; s) yield e3

// translated to
e1.flatMap(x => for (y <- e2; s) yield e3)

forとPattern Matching
前の記事(JSON表現)の例と結びつけて、forでmap、filterの操作をします.
val data: List[JSON] = ...
for {
  JObj(bindings) <- data
  JSeq(phones) = bindings("phoneNumbers")
  JObj(phone) <- phones
  JStr(digits) = phone("number")
  if digits startsWith "212"
} yield (bindings("firstName"), bindings("lastName"))

forの中のPattern Matchingの大まかな翻訳過程:
pat <- expr
// to
x <- expr withFilter {
    case pat => true
    case _ => false
  } map {
    case pat => x
  }

Exercise
for {
  x <- 2 to N
  y <- 2 to x
  if (x % y == 0)
} yield (x, y)

次のように翻訳できます.
(2 to N) flatMap (x =>
  (2 to x) withFilter (y =>
    x % y == 0) map (y => (x, y)))

参照Principles of Reactive Programming
全文完了:)