在我看来,我写了一个简单的Scala代码,这是一个Monad实现.
这是一个基本特征:
trait M[A] {
def unit(x: A): M[A]
def bind[B](f: A => M[B]): M[B]
}
Run Code Online (Sandbox Code Playgroud)
执行:
case class Monad(e: String) extends M[String] {
def unit(x: String): M[String] = {
Monad(x)
}
def bind[B](f: (String) => M[B]): M[B] = {
f(e)
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以确认它是否是真正的Monad实现?
这不是一个单子,因为它有错误的类型.应该为具有单个类型参数的类型构造函数定义monad特征,例如
trait Monad[M[_]] {
def unit[A](a: A): M[A]
def bind[A, B](ma: M[A], bf: A => M[B]): M[B]
}
Run Code Online (Sandbox Code Playgroud)
注意方法unit和bind是在"值"类型的通用A和B.
那么你的实现应该是针对特定类型的构造函数(例如,Option,List)
implicit object ObjectMonad extends Monad[Option] {
def unit[A](a: A) = Some(a)
def bind[A, B](oa: Option[A], bf: A => Option[B]): Option[B] = {
oa match {
case Some(a) => bf(a)
case None => None
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |