要学习如何创建monad并了解其内部机制,我正在尝试通过以下这篇令人敬畏的文章来实现Writer的版本:You Could Have Invented Monads!
我面临的问题是我无法使用在a中创建的数据结构进行理解。
这是我的代码的摘要:
case class Writer( x: Double, log: String = " Beginning of log") {
def flatMap( f: Double => Writer ): Writer = f( x ) match {
case Writer( fx, msg ) => Writer( fx, log + "\n " + msg )
}
def map( f: Double => Double ): Double = f( x )
}
def outer( x: Double ) = Writer( Math.log( x ), s"Called outer($x)" )
def inner( x: Double ) = Writer( Math.exp( x ), s"Called inner($x)" )
def example( x: Double ): Unit = {
// This works
val result = Writer( x ).flatMap {
y1 => inner(y1).flatMap { y2 => outer(y2) }
}
println( result )
// This works
val result2 = for { y1 <- Writer(x) } yield {
for { y2 <- inner( y1 ) } yield {
for { y3 <- outer( y2 ) } yield y3
}
}
println( result2 )
// THIS DOESN'T WORK
val result3 = for {
y1 <- Writer(x)
y2 <- inner( y1 )
y3 <- outer( y2 )
} yield y3 // Or whatever, it doesn't work
println( result3 )
}
我的完整代码在这里:Debuggable.scala
我不知道是什么我的代码中缺少的内容。 就像scalaz实现返回的内容对于理解很有帮助,然后您使用特定的方法运行它。但是我自己找不到怎么做