这是Monad实施吗?

时间:2015-10-01 21:41:41

标签: scala monads

在我看来,我写了一个简单的Scala代码,这是Monad实现。

这是一个基本特征:

trait M[A] {

  def unit(x: A): M[A]

  def bind[B](f: A => M[B]): M[B]

}

实现:

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)
  }    

}

有人可以确认这是否是真正的Monad实现?

1 个答案:

答案 0 :(得分:5)

这不是一个单子,因为它有错误的类型。应该为具有单个类型参数的类型构造函数定义monad特征,例如

15_Books_Base_count.py starts here......

Book_10 Record Count = 841
Book_20 Record Count = 209
Book_30 Record Count = 56
Book_40 Record Count = 32182
Book_50 Record Count = 40178
Book_60 Record Count = 8562
Book_70 Record Count = 2118
Book_80 Record Count = 6413
Book_90 Record Count = 645

FeatureClasses found = 11

请注意,trait Monad[M[_]] { def unit[A](a: A): M[A] def bind[A, B](ma: M[A], bf: A => M[B]): M[B] } unit方法在'值'中是通用的。类型bindA

那么你的实现应该是针对特定类型的构造函数(例如Option,List),例如

B