【问题标题】:Adding Haskell's Monadic Bind Operator to Scala将 Haskell 的 Monadic 绑定运算符添加到 Scala
【发布时间】:2011-03-25 17:47:48
【问题描述】:

在 Haskell 中,您可以像这样使用绑定运算符 (>>=):

repli :: [a] -> [a]
repli xs = xs >>= \x -> [x,x]

*Main> repli [1,2,3]
[1,1,2,2,3,3]

我读到flatMap 是 Scala 的绑定运算符:

def repli [A](xs: List[A]): List[A] =
  xs.flatMap { x => List(x,x) }

scala> repli (List(1,2,3))
res0: List[Int] = List(1, 1, 2, 2, 3, 3)

作为教学练习,我正在尝试向 Scala 添加对 >>= 的支持:

class MyList[T](list: List[T]) {
  def >>= [U](f: T => List[U]): List[U] = list.flatMap(f)
}
implicit def list2mylist[T](list: List[T]) = new MyList(list)

def repliNew [A](xs: List[A]): List[A] =
  xs >>= { x: A => List(x,x) }

scala> repliNew (List(1,2,3))
res1: List[Int] = List(1, 1, 2, 2, 3, 3)

这非常有效,但仅适用于列表。我真的很想用flatMap 方法支持任何类。解决这个问题的最佳方法是什么?

【问题讨论】:

  • (scalaz 中的任何相关内容?)
  • 如果你只对集合层次结构的成员没问题——例如不是Option没有额外的工作--那么你可以使用stackoverflow.com/questions/5410846中显示的方法
  • +1 教我一个新词:教育学

标签: scala haskell monads implicit-conversion


【解决方案1】:

Scalaz 如下:

trait MA[M[_], A] {
  def value: M[A]
  def >>=(f: A => M[B])(implicit m: Monad[M]): M[B] =
    m.bind(value, f)
}

对于所有 M[_] 和 A,从 M[A] 到 MA[M, A] 的隐式转换:

implicit def ma[M[_], A](m: => M[A]): MA[M, A] = new MA[M, A] {
  lazy val value = m
}

你只需要一个 trait Monad 和你关心的每个 monad 的一个实例:

trait Monad[M[_]] {
  def pure[A](a: => A): M[A]
  def bind[A, B](m: M[A], f: A => M[B]): M[B]
}

【讨论】:

    【解决方案2】:

    使用隐式类添加 flatMap 的同义词怎么样?

    implicit class BindRich[A,B](fm:{def flatMap(a:A):B}) {
      def >>=(a:A):B = fm.flatMap(a)
    }
    

    在 this 范围内,任何具有 flatMap 方法的对象也将具有 >>=。

    【讨论】:

    • 请注意,这可能会在后台使用反射。
    猜你喜欢
    • 2012-06-15
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2012-07-05
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多