Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active February 15, 2024 11:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/65200623b7349ccba366593a73378ccb to your computer and use it in GitHub Desktop.
Save fancellu/65200623b7349ccba366593a73378ccb to your computer and use it in GitHub Desktop.
Example of Tree Functor usage in Cats
Branch(990,Leaf(1230),Branch(1000,Leaf(20),Leaf(30)))
Branch(990!,Leaf(1230!),Branch(1000!,Leaf(20!),Leaf(30!)))
Branch(!099,Leaf(!0321),Branch(!0001,Leaf(!02),Leaf(!03)))
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] = func.map(f)(_ * 10)
def addBang[F[_]](f: F[String])(implicit func: Functor[F]): F[String] = func.map(f)(_+"!")
val multiplied = times10(tree)
println(multiplied)
val excited = addBang(TreeFunctor.map(multiplied)(_.toString))
println(excited)
import cats.syntax.functor._
val reversed=excited.map(_.reverse)
println(reversed)
}
}
@fancellu
Copy link
Author

fancellu commented Sep 3, 2021

A similar example, but with a custom LinkedList

https://gist.github.com/fancellu/91a948d1042f996cf843f7090df62ae7

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