Fun with Functors

Karl Bielefeldt

Lists

  • val in  = List(1, 2, 3)
  • val out = List("1", "2", "3")
  • in map {_.toString}

Options

  • val in: Option[Int] = None
  • val out = None
  • val in  = Some(1)
  • val out = Some("1")
  • in map {_.toString}

Eithers

  • val in: Either[Exception,Int] = Left(new Exception())
  • val out = Left(new Exception())
  • val in  = Right(1)
  • val out = Right("1")
  • in map {_.toString}

Functions

  • val in = (x: Int) => x + 1
  • val out =
      (x: Int) => (x + 1).toString
  • in map {_.toString}

Referring to them together?

Mappable

Mappable

Functor

Tree[A]

  • def map[B](f: (A) => B): Tree[B] = ???
  • def map[B](f: (A) => B): Tree[B] = Tree.empty[B]

Functor Laws

  • in map identity == in
  • (f compose g).map ==
    f.map compose g.map

What are they good for?

  • val in = Future.successful(List(Some(1), None, Some(3)))
  • val futListOpt = Functor[Future] compose Functor[List] compose Functor[Option]
  • futListOpt.map(in)(_.toString)

Thank you