Skip to content

Instantly share code, notes, and snippets.

Last active September 14, 2021 20:31
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Example of Tree Functor usage in Cats
import cats._
object TreeFunctorExample {
def main(args: Array[String]): Unit = {
sealed trait Tree[+T]
case class Leaf[+T](value: T) extends Tree[T]
case class Branch[+T](value: T, left: Tree[T], right: Tree[T]) extends Tree[T]
// casting up because of cats invariance
object Tree {
def leaf[T](v: T): Tree[T] = Leaf(v)
def branch[T](v: T, l: Tree[T], r: Tree[T]): Tree[T] = Branch(v, l, r)
import Tree._
implicit object TreeFunctor extends Functor[Tree] {
override def map[A, B](fa: Tree[A])(f: A => B): Tree[B] = fa match {
case Leaf(v) => Leaf(f(v))
case Branch(v, l, r) => Branch(f(v), map(l)(f), map(r)(f))
val tree = branch(99, leaf(123), branch(100, leaf(2), leaf(3)))
def times10[F[_]](f: F[Int])(implicit func: Functor[F]): F[Int] = * 10)
def addBang[F[_]](f: F[String])(implicit func: Functor[F]): F[String] ="!")
val multiplied = times10(tree)
val excited = addBang(
import cats.syntax.functor._
Copy link

fancellu commented Sep 3, 2021

A similar example, but with a custom LinkedList

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment