【发布时间】:2019-10-03 18:48:00
【问题描述】:
试图了解如何最好地处理 FP 中的副作用。
我实现了这个基本的 IO 实现:
trait IO[A] {
def run: A
}
object IO {
def unit[A](a: => A): IO[A] = new IO[A] { def run = a }
def loadFile(fileResourcePath: String) = IO.unit[List[String]]{
Source.fromResource(fileResourcePath).getLines.toList }
def printMessage(message: String) = IO.unit[Unit]{ println(message) }
def readLine(message:String) = IO.unit[String]{ StdIn.readLine() }
}
我有以下用例:
- load lines from log file
- parse each line to BusinessType object
- process each BusinessType object
- print process result
案例 1: 所以 Scala 代码可能看起来像这样
val load: String => List[String]
val parse: List[String] => List[BusinessType]
val process: List[BusinessType] => String
val output: String => Unit
案例 2: 我决定使用上面的 IO:
val load: String => IO[List[String]]
val parse: IO[List[String]] => List[BusinessType]
val process: List[BusinessType] => IO[Unit]
val output: IO[Unit] => Unit
在情况 1 中,负载是不纯的,因为它是从文件中读取的,所以输出也是不纯的,因为它正在将结果写入控制台。
为了更实用,我使用案例 2。
问题:
- Aren't case 1 and 2 really the same thing?
- In case 2 aren't we just delaying the inevitable?
as the parse function will need to call the io.run
method and cause a side-effect?
- when they say "leave side-effects until the end of the world"
how does this apply to the example above? where is the
end of the world here?
【问题讨论】:
标签: scala functional-programming monads