帮助我了解以下Scala代码:scalaz IO Monad [英] Help me understand this Scala code: scalaz IO Monad
问题描述
Here's the code I'm trying to understand (it's from http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/):
object io {
sealed trait IO[A] {
def unsafePerformIO: A
}
object IO {
def apply[A](a: => A): IO[A] = new IO[A] {
def unsafePerformIO = a
}
}
implicit val IOMonad = new Monad[IO] {
def pure[A](a: => A): IO[A] = IO(a)
def bind[A,B](a: IO[A], f: A => IO[B]): IO[B] = IO {
implicitly[Monad[Function0]].bind(() => a.unsafePerformIO,
(x:A) => () => f(x).unsafePerformIO)()
}
}
}
此代码的用法如下(我假设隐含import io._
)
This code is used like this (I'm assuming an import io._
is implied)
def bufferFile(f: File) = IO { new BufferedReader(new FileReader(f)) }
def closeReader(r: Reader) = IO { r.close }
def bracket[A,B,C](init: IO[A], fin: A => IO[B], body: A => IO[C]): IO[C] = for { a <- init
c <- body(a)
_ <- fin(a) } yield c
def enumFile[A](f: File, i: IterV[String, A]): IO[IterV[String, A]] = bracket(bufferFile(f),
closeReader(_:BufferedReader),
enumReader(_:BufferedReader, i))
让我们从bufferFile
定义开始.我认为调用io.IO的apply
方法是否正确?该apply
方法采用无参数函数,该函数返回一个值(正确吗?).我想这就是我要坚持的地方.有人可以解释bufferFile
的定义如何工作吗?
Let's start with the bufferFile
definition. Am I correct in thinking that the apply
method of io.IO is called? That apply
method takes a parameterless function that returns a value (correct?). I guess this is where I'm stuck. Can someone explain how the definition of bufferFile
works?
推荐答案
是的,您说得对,几乎可以; io.IO.apply
用所谓的按名称"参数调用,该参数基本上是一个不占用任何内容(Unit
)并返回A
的函数.有趣的是,当您像new BufferedReader(new FileReader(f))
这样直接传递A
的实例时,它将转换为类似() => new BufferedReader(new FileReader(f))
的事物.
Yes you are right, well almost; io.IO.apply
gets called with a so called "by name" parameter which is basically a function which takes nothing (Unit
) and returns A
. The cool thing about is that when you pass an instance of A
directly like new BufferedReader(new FileReader(f))
, it will be converted to something like () => new BufferedReader(new FileReader(f))
.
作为apply
的结果,您将获得IO[BufferedReader]
的实例,该实例定义了方法def unsafePerformIO
,该方法仅返回捕获的BufferedReader
的实例.
As a result of apply
you get an instance of an IO[BufferedReader]
which defines a method def unsafePerformIO
which simply returns the instance of the captured BufferedReader
.
这篇关于帮助我了解以下Scala代码:scalaz IO Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!