Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created May 14, 2020 16:07
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/91a948d1042f996cf843f7090df62ae7 to your computer and use it in GitHub Desktop.
Save fancellu/91a948d1042f996cf843f7090df62ae7 to your computer and use it in GitHub Desktop.
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