scala – 值映射不是Branch [Int]的成员
发布时间:2020-12-16 18:14:33 所属栏目:安全 来源:网络整理
导读:我有以下ADT: import cats.Functorsealed 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 def treeFunctor = new Functor[Tree
我有以下ADT:
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] 并在仿函数中执行: implicit def treeFunctor = new Functor[Tree] { def map[A,B](fa: Tree[A])(f: (A) => B): Tree[B] = fa match { case Branch(left,right) => Branch(map(left)(f),map(right)(f)) case Leaf(v) => Leaf(f(v)) } } 并使用如下: val b = Branch(left = Branch(Branch(Leaf(5),Leaf(3)),Leaf(10)),Leaf(45)) val functorTree = Functor[Tree].map(b)((v) => v * 4) 但是以下: Branch(Leaf(10),Leaf(20)).map(_ * 2) 我有编译器错误: Error:(21,29) value map is not a member of A$A90.this.Branch[Int] Branch(Leaf(10),Leaf(20)).map(_ * 2) ^ 我的问题是为什么我会收到错误? 解决方法
方法treeFunctor为您提供任何Tree的Functor [Tree]实例,但这并不意味着任何Tree会自动转换为它.只是对于任何树,你在范围内都有一个Functor [Tree]的隐式实例.
这个隐式实例有一个方法映射,它有两个参数:要映射的Functor [Tree]的实例,以及映射函数本身. 所以这应该工作: implicitly[Functor[Tree]].map(Branch(Leaf(10),Leaf(20)))(_ * 2) 或者干脆 Functor[Tree].map(Branch(Leaf(10),Leaf(20)))(_ * 2) (因为scalaz和猫通常有类型类的方便apply()) 编辑:在阅读你的问题时,我错过了Functor [Tree] .map(b)((v)=> v * 4)部分.所以你真正感兴趣的是以下部分. 如果要保留调用map的语法,可以创建一个隐式类作为包装器: implicit class toTreeFunctor[A](tree: Tree[A]) { def map[B](f: A => B) = Functor[Tree].map(tree)(f) } Branch(Leaf(10),Leaf(20)).map(_ * 2) 正如@P所指出的那样. Frolov,您可以从导入scalaz.syntax.functor._免费获取此隐式转换,或者导入cats.syntax.functor._,但请注意,您必须明确地将您的Branch更新为Tree的实例. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |