Cats: Non tail recursive tailRecM method for Monads

时间:2017-06-12 16:53:25

标签: scala recursion functional-programming scala-cats

In cats, when a Monad is created using Monad trait, an implementation for method tailRecM should be provided.

I have a scenario below that I found impossible to provide a tail recursive implementation of tailRecM

  sealed trait Tree[+A]

  final case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]

  final case class Leaf[A](value: A) extends Tree[A]

  implicit val treeMonad = new Monad[Tree] {

    override def pure[A](value: A): Tree[A] = Leaf(value)

    override def flatMap[A, B](initial: Tree[A])(func: A => Tree[B]): Tree[B] =
      initial match {
        case Branch(l, r) => Branch(flatMap(l)(func), flatMap(r)(func))
        case Leaf(value) => func(value)
      }

    //@tailrec
    override def tailRecM[A, B](a: A)(func: (A) => Tree[Either[A, B]]): Tree[B] = {
      func(a) match {
        case Branch(l, r) =>
          Branch(
            flatMap(l) {
              case Right(l) => pure(l)
              case Left(l) => tailRecM(l)(func)
            },
            flatMap(r){
              case Right(r) => pure(r)
              case Left(r) => tailRecM(r)(func)
            }
          )

        case Leaf(Left(value)) => tailRecM(value)(func)

        case Leaf(Right(value)) => Leaf(value)
      }
    }
  }

1) According to the above example, how this tailRecM method can be used for optimizing flatMap method call? Does the implementation of the flatMap method is overridden/modified by tailRecM at the compile time ?

2) If the tailRecM is not tail recursive as above, will it still be efficient than using the original flatMap method ?

Please share your thoughts.

2 个答案:

答案 0 :(得分:8)

有时候有一种方法可以用显式列表替换调用堆栈。

此处toVisit会跟踪等待处理的分支。

toCollect保留等待合并的分支,直到完成相应的分支处理。

override def tailRecM[A, B](a: A)(f: (A) => Tree[Either[A, B]]): Tree[B] = {
  @tailrec
  def go(toVisit: List[Tree[Either[A, B]]],
         toCollect: List[Tree[B]]): List[Tree[B]] = toVisit match {
    case (tree :: tail) =>
      tree match {
        case Branch(l, r) =>
          l match {
            case Branch(_, _) => go(l :: r :: tail, toCollect)
            case Leaf(Left(a)) => go(f(a) :: r :: tail, toCollect)
            case Leaf(Right(b)) => go(r :: tail, pure(b) +: toCollect)
          }
        case Leaf(Left(a)) => go(f(a) :: tail, toCollect)
        case Leaf(Right(b)) =>
          go(tail,
             if (toCollect.isEmpty) pure(b) +: toCollect
             else Branch(toCollect.head, pure(b)) :: toCollect.tail)
      }
    case Nil => toCollect
  }

  go(f(a) :: Nil, Nil).head
}

cats ticket开始使用tailRecM

  对于猫中的任何Monads,tailRecM都不会破坏堆栈(就像它可能是OOM的几乎所有JVM程序一样)。

然后

  

没有tailRecM(或递归flatMap)是安全的,库就像   iteratee.io无法安全地编写,因为它们需要monadic递归。

another ticket指出cats.Monad的客户应该知道某些monad没有stacksafe tailRecM

  

tailRecM仍然可以被那些试图获得堆栈安全性的人使用,只要他们知道某些monad将无法将它们提供给他们

答案 1 :(得分:7)

tailRecMflatMap之间的关系

为回答您的第一个问题,以下代码是FlatMapLaws.scalacats-laws的一部分。它测试flatMaptailRecM方法之间的一致性。

/**
 * It is possible to implement flatMap from tailRecM and map
 * and it should agree with the flatMap implementation.
 */
def flatMapFromTailRecMConsistency[A, B](fa: F[A], fn: A => F[B]): IsEq[F[B]] = {
  val tailRecMFlatMap = F.tailRecM[Option[A], B](Option.empty[A]) {
    case None => F.map(fa) { a => Left(Some(a)) }
    case Some(a) => F.map(fn(a)) { b => Right(b) }
  }

  F.flatMap(fa)(fn) <-> tailRecMFlatMap
}

这显示了如何从flatMap实现tailRecM,并暗示了编译器不会自动执行此操作。由Monad的用户决定何时在tailRecM上使用flatMap才有意义。

This blog有不错的scala示例,用于说明何时tailRecM有用。它遵循最初介绍该方法的Phil Freeman的PureScript article

它说明了将flatMap用于单峰成分的缺点:

  

Scala的这一特性限制了flatad可以调用monadic函数f,然后可以调用flatMap等的monadic组合的用途。

与基于tailRecM的实现相反:

  

这可以确保FlatMap类型类的用户获得更大的安全性,但这意味着每个实例的实现者都需要提供安全的tailRecM。

在猫中提供的许多方法都利用单子组成。因此,即使您不直接使用它,实现tailRecM也可以与其他monad进行更有效的合成。

树的放大

在另一个答案中,@ nazarii-bardiuk提供了tailRecM的实现,该实现是尾递归的,但未通过上述的flatMap / tailRecM一致性测试。递归后无法正确重建树结构。下面是一个固定版本:

def tailRecM[A, B](arg: A)(func: A => Tree[Either[A, B]]): Tree[B] = {
  @tailrec
  def loop(toVisit: List[Tree[Either[A, B]]], 
           toCollect: List[Option[Tree[B]]]): List[Tree[B]] =
    toVisit match {
      case Branch(l, r) :: next =>
        loop(l :: r :: next, None :: toCollect)

      case Leaf(Left(value)) :: next =>
        loop(func(value) :: next, toCollect)

      case Leaf(Right(value)) :: next =>
        loop(next, Some(pure(value)) :: toCollect)

      case Nil =>
        toCollect.foldLeft(Nil: List[Tree[B]]) { (acc, maybeTree) =>
          maybeTree.map(_ :: acc).getOrElse {
            val left :: right :: tail = acc
            branch(left, right) :: tail
          }
        }
    }

  loop(List(func(arg)), Nil).head
}

gist with test

您可能知道,但是您的示例(以及@ nazarii-bardiuk的回答)在Noel Welsh和Dave Gurnell的书Scala with Cats中使用(强烈推荐)。

相关问题