Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of Functor usage in Cats for a custom type vs standard List
import cats._
import cats.data._
import cats.syntax._
import cats.implicits._
object CatFunc extends App {
// a very naive linked list implementation and functor for it
trait MyList[+A]
case class MyNode[A]( head: A, tail: MyList[A]) extends MyList[A]
case object MyNil extends MyList[Nothing]
implicit val functor1=new Functor[MyList]{
override def map[A, B](fa: MyList[A])(f: A => B): MyList[B] = fa match{
case MyNode(head, tail)=> MyNode(f(head),map(tail)(f))
case MyNil => MyNil
}
}
def doStuff[F[_]](li: F[Int])(implicit ev: Functor[F])={
println(li.map(_+10))
println(li.void)
println(li.as(999))
println(li.tupleLeft(100))
println(li.tupleRight(200))
// there is no syntax for ifF, so we use direct from the Functor
println(ev.ifF(li.map(_>1))(
"yes", "no"
))
}
// against a normal List of Ints
doStuff(List(1,2))
// against a MyList of Ints
val li:MyList[Int]=MyNode(1,MyNode(2,MyNil))
doStuff(li)
}
List(11, 12)
List((), ())
List(999, 999)
List((100,1), (100,2))
List((1,200), (2,200))
List(no, yes)
MyNode(11,MyNode(12,MyNil))
MyNode((),MyNode((),MyNil))
MyNode(999,MyNode(999,MyNil))
MyNode((100,1),MyNode((100,2),MyNil))
MyNode((1,200),MyNode((2,200),MyNil))
MyNode(no,MyNode(yes,MyNil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.