-
Notifications
You must be signed in to change notification settings - Fork 9
For Comprehensions(二)
Song Kun edited this page Jan 19, 2018
·
2 revisions
Scala 的 for
表达式对应于 Haskell 的 do
表达式,仅仅是 flatMap
map
withFilter
/filter
和 foreach
等 monadic 组合子的语法糖而已,所有 for
表达式都会被转换为这 3 个组合子的组合。
https://docs.scala-lang.org/tutorials/FAQ/yield.html
case class Id[A](v: A) {
def map[B](f: A => B): Id[B] = Id(f(v))
def flatMap[B](f: A => Id[B]): Id[B] = f(v)
}
for {
a <- Id("hello")
b <- Id(" world")
} yield a + b
Id("hello") flatMap {
a => Id(" world") flatMap {
b => Id(a + b)
}
}
Id("hello") flatMap {
a => Id(" world") map {
b => a + b
}
}