【问题标题】:Cannot Resolve Map in a Functor Defined for Binary Tree无法解析为二叉树定义的函子中的映射
【发布时间】:2020-06-27 11:30:29
【问题描述】:

我正在做“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)

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

发生了什么,我该如何解决?据我所知,我有一个与书中提供的解决方案等效的解决方案。

【问题讨论】:

    标签: scala functional-programming typeclass functor scala-cats


    【解决方案1】:

    import cats.implicits._ 缺失,这为您提供了Ops 扩展方法

    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)
    

    如果没有范围内的扩展方法,您可以使用带有主方法 convention 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))
    

    【讨论】:

    • 谢谢@Mario,我在摸不着头脑,但你的回答让我明白了!
    • @finite_diffidence 在学习的同时,您可能只想导入必要的最小值而不是整个隐式,因此您可以只导入 import cats.syntax.functor._;这对于理解每件事的位置很有用,但通常在实际开发中,您通常只会导入所有隐式。
    • 谢谢@LuisMiguelMejíaSuárez 我会继续这样做!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2019-01-18
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多