无法解析为二叉树定义的函子中的映射

Cannot Resolve Map in a Functor Defined for Binary Tree

我正在做“Scala with Cats”一书中的 Functor 练习。其中一个练习是为二叉树定义一个函子。

这是我的尝试(我将这段代码放在 scala 工作表中):

import cats.Functor

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]

object Tree {
  def branch[A](left: Tree[A], right: Tree[A]): Tree[A] = {
    Branch(left, right)
  }

  def leaf[A](value: A): Tree[A] = {
    Leaf(value)
  }
}

implicit val treeFunctor: Functor[Tree] = new Functor[Tree] {
  def map[A, B](value: Tree[A])(func: A => B): Tree[B] = {
    value match {
      case l: Leaf[A] => Leaf(func(l.value))
      case b: Branch[A] => Branch(map(b.left)(func), map(b.right)(func))
    }
  }
}

Tree.branch(Tree.leaf(10), Tree.leaf(20)).map(_ * 2)

失败,在最后一行显示“无法解析符号映射”。

这是怎么回事,我该如何解决?据我所知,我有一个与书中提供的解决方案等效的解决方案。

import cats.implicits._ 丢失,这给了你 扩展方法

import cats.implicits._
Tree.branch(Tree.leaf(10), Tree.leaf(20)).map(_ * 2)
// res0: Tree[Int] = Branch(Leaf(20),Leaf(40))

这是有效的,因为它扩展到

toFunctorOps(Tree.branch(Tree.leaf(10), Tree.leaf(20)))(treeFunctor).map(_ * 2)

如果范围内没有扩展方法,您可以使用主方法 Functor.apply[Tree]

使用伴生对象来召唤 treeFunctor 实例
val tree = Tree.branch(Tree.leaf(10), Tree.leaf(20))
Functor[Tree].map(tree)(_ * 2)
// res0: Tree[Int] = Branch(Leaf(20),Leaf(40))