2014年7月12日 星期六

scala 中 for ...yield 與 map, flatMap, withFilter 之互換


-------------------------------
for(x <- expr1) yield expr2
expr1.map(x => expr2)

-------------------------------

for(x <- expr1 if expr2) expr3
expr1.withFilter(x => expr2).map(x => expr3)

-------------------------------

for(x <- expr1 if expr2; seq) yield expr3
for(x <- expr1 withFilter expr2; seq) yield expr3

-------------------------------

for(x <- expr1; y <- expr2; seq) yield expr3
expr1.flatMap(x => for (y <- expr2; seq) yield expr3)

-------------------------------


for ((x1, x2) <- expr1) yield expr2
expr1.map{case(x1, x2) => expr2}

-------------------------------

for(pat <- expr1) yield2

expr1 withFilter {
  case pat = > true
  case _ => false
} map {
  case pat => expr2
}

沒有留言:

張貼留言