Monad在斯卡拉的特质 [英] Monad trait in Scala

查看:115
本文介绍了Monad在斯卡拉的特质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(How)是否有可能以通用的方式在Scala中表示monad(比如Haskell中的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆