Why can find `Functor` instance for Tree but not for Branch or Leaf?

て烟熏妆下的殇ゞ 提交于 2019-12-11 07:11:36

问题


I have the following Functor definition:

import cats.Functor
import cats.syntax.functor._

object Theory {

  implicit val treeFunctor: Functor[Tree] =
    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(value) =>
            Leaf(f(value))
        }
    }

  def main(args: Array[String]): Unit = {
    Branch(Leaf(10), Leaf(20)).map(_ * 2)
  }


}

for:

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]

Why the compiler complains:

// <console>:42: error: value map is not a member of wrapper.Branch[
Int]
//
Branch(Leaf(10), Leaf(20)).map(_ * 2)
//

So I have to create a smart constructor:

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)
}

What is a smart constructor in this case?


回答1:


The declaration of Functor[F[_]] in cats is invariant in F. Therefore, a Functor[Tree] is neither a generalization, nor a specialization of Functor[Branch]. These types are unrelated.

The problem with your code is the following. The expression

Branch(Leaf(10), Leaf(20))

is of type Branch[Int]. When you try to apply .map[X] to it directly, you signal that you would like to get a Branch[X] as the result. But there is no Functor[Branch] in scope (it's not like you couldn't write one, but as it stands, there is none).

In order to make use of the Functor[Tree], you have to make it clear to the compiler that you want to treat this instance as Tree[Int]. Casting would work. Or using a custom factory method that hides Branch and exposes Tree would work too: that's what the "smart" constructor is doing.




回答2:


You can use kittens and implement instances for Branch and Leaf, then the instance for Tree can be derived.

libraryDependencies += "org.typelevel" %% "kittens" % "1.0.0-RC2"

  import cats.Functor
  import cats.syntax.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 val treeFunctor: Functor[Tree] = cats.derive.functor[Tree]

  implicit val branchFunctor: Functor[Branch] =
    new Functor[Branch] {
      def map[A, B](fa: Branch[A])(f: A => B): Branch[B] =
        fa match {
          case Branch(left, right) =>
            Branch(left.map(f), right.map(f))
        }
    }

    // or without extension method
//  implicit def branchFunctor(implicit treeFunctor: Functor[Tree]): Functor[Branch] =
//    new Functor[Branch] {
//      def map[A, B](fa: Branch[A])(f: A => B): Branch[B] =
//        fa match {
//          case Branch(left, right) =>
//            Branch(treeFunctor.map(left)(f), treeFunctor.map(right)(f))
//        }
//    }

  implicit val leafFunctor: Functor[Leaf] =
    new Functor[Leaf] {
      def map[A, B](fa: Leaf[A])(f: A => B): Leaf[B] =
        fa match {
          case Leaf(value) =>
            Leaf(f(value))
        }
    }

  def main(args: Array[String]): Unit = {
    (Branch(Leaf(10), Leaf(20)): Tree[Int]).map(_ * 2)
    Branch(Leaf(10), Leaf(20)).map(_ * 2)
    Leaf(10).map(_ * 2)
  }

Actually then you can derive all three instances:

  implicit val treeFunctor: Functor[Tree] = cats.derive.functor[Tree]
  implicit val leafFunctor: Functor[Leaf] = cats.derive.functor[Leaf]
  implicit val branchFunctor: Functor[Branch] = cats.derive.functor[Branch]

  def main(args: Array[String]): Unit = {
    (Branch(Leaf(10), Leaf(20)): Tree[Int]).map(_ * 2)
    Branch(Leaf(10), Leaf(20)).map(_ * 2)
    Leaf(10).map(_ * 2)
  }


来源:https://stackoverflow.com/questions/48545028/why-can-find-functor-instance-for-tree-but-not-for-branch-or-leaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!