Monad在斯卡拉的特质 [英] Monad trait in Scala
问题描述
Monad
typeclass)?是否有可能为此目的而定义 trait Monad
? 你可以试试这样:
](a:A):M [A]def bind [A,B](m:M [A])(f:A => M [B]):M [B]
}
//可能只适用于Scala 2.8
implicit def monadicSyntax [M [_],A](m:M [A])(implicit tc:Monad [M]) = new {
private val bind = tc.bind(m)_
def map [B](f:A => B)= bind(f compose tc.unit)
def flatMap [B](f:A => M [B])= bind(f)
}
隐式对象MonadicOption扩展Monad [Option] {
def unit [A](a:A)=一些(a)
def bind [A,B](opt:Option [A])(f:A => Option [B])= opt flatMap f
}
您当然会定义类似的隐式你心中渴望的任何其他单体的物体。在Haskell的术语中,可以将类型类型和 MonadicOption
作为该类型的特定实例,将 Monad
monadicSyntax
隐式转换简单地演示了这种类型类型如何用于允许Scala的用于
-comprehensions和任何满足 Monad
类型类。
一般而言,Scala标准库中的大部分功能都实现 flatMap
是单子。 Scala没有定义一个通用的 Monad
typeclass(尽管这非常有用)。相反,它依赖于解析器的语法技巧来允许 -comprehensions和 使用来实现适当的方法。具体来说,这些方法是
map ,
flatMap
和过滤器
(或 foreach
和过滤器
命令式表单)。
(How) is it possible to represent monads in Scala in a generic way (like the Monad
typeclass in Haskell)? Is it somehow possible to define a trait Monad
for this purpose?
You could try something like this:
trait Monad[+M[_]] {
def unit[A](a: A): M[A]
def bind[A, B](m: M[A])(f: A => M[B]): M[B]
}
// probably only works in Scala 2.8
implicit def monadicSyntax[M[_], A](m: M[A])(implicit tc: Monad[M]) = new {
private val bind = tc.bind(m) _
def map[B](f: A => B) = bind(f compose tc.unit)
def flatMap[B](f: A => M[B]) = bind(f)
}
implicit object MonadicOption extends Monad[Option] {
def unit[A](a: A) = Some(a)
def bind[A, B](opt: Option[A])(f: A => Option[B]) = opt flatMap f
}
You would of course define similar implicit objects for any other monad your heart desires. In Haskell terms, you can think of Monad
like the typeclass and MonadicOption
as a particular instance of that type class. The monadicSyntax
implicit conversion simply demonstrates how this typeclass could be used to allow the use of Scala's for
-comprehensions with anything which satisfies the Monad
typeclass.
Generally speaking, most things in the Scala standard library which implement flatMap
are monads. Scala doesn't define a generic Monad
typeclass (though that would be very useful). Instead, it relies on a syntactic trick of the parser to allow the use of for
-comprehensions with anything which implements the appropriate methods. Specifically, those methods are map
, flatMap
and filter
(or foreach
and filter
for the imperative form).
这篇关于Monad在斯卡拉的特质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!