【发布时间】:2014-02-15 16:54:03
【问题描述】:
查看来自Functional Programming in Scala 的 IO Monad 示例:
def ReadLine: IO[String] = IO { readLine }
def PrintLine(msg: String): IO[Unit] = IO { println(msg) }
def converter: IO[Unit] = for {
_ <- PrintLine("enter a temperature in degrees fahrenheit")
d <- ReadLine.map(_.toDouble)
_ <- PrintLine((d + 32).toString)
} yield ()
我决定用flatMap 重写converter。
def converterFlatMap: IO[Unit] = PrintLine("enter a temperate in degrees F").
flatMap(x => ReadLine.map(_.toDouble)).
flatMap(y => PrintLine((y + 32).toString))
当我将最后一个flatMap 替换为map 时,我没有看到控制台上打印出readLine 的结果。
与flatMap:
enter a temperate in degrees
37.0
与map:
enter a temperate in degrees
为什么?另外,签名(IO[Unit])与map 或flatMap 仍然相同吗?
这是本书中的IO monad。
sealed trait IO[A] { self =>
def run: A
def map[B](f: A => B): IO[B] =
new IO[B] { def run = f(self.run) }
def flatMap[B](f: A => IO[B]): IO[B] =
new IO[B] { def run = f(self.run).run }
}
【问题讨论】: