Search code examples
scalafunctional-programmingcompositionfunctorscalaz

Examples of Functors composition


This is a follow-up to an answer to my previous question.

We know that functors compose. I can write a composition of functors List[_] and Option[_] using scalaz like this:

import scalaz._, Scalaz._

scala> val flist = Functor[List]
flist: scalaz.Functor[List] = scalaz.std.ListInstances$$anon$1@a5f0295

scala> val foption = Functor[Option]
foption: scalaz.Functor[Option] = scalaz.std.OptionInstances$$anon$1@51e43ad4

scala> flist compose foption
res0: scalaz.Functor[[α]List[Option[α]]] = scalaz.Functor$$anon$1@94c02b

scala> val f = flist compose foption
f: scalaz.Functor[[α]List[Option[α]]] = scalaz.Functor$$anon$1@610bffa0

scala> val os: List[Option[Int]] = Some(1) :: Some(2) :: None :: Nil
os: List[Option[Int]] = List(Some(1), Some(2), None)

scala> f.map(os) {_ + 1}
res1: List[Option[Int]] = List(Some(2), Some(3), None)

Is it the correct way to compose functors with scalaz ?
Could you give a real-life example of a functors composition ?


Solution

  • Suppose that you have a list of strings, where each string is a list of characters. By composing the two list functors, you get one functor over lists of strings. You can now map functions on characters, like, say, toUpper or toLower, to the list of strings.

    Is this example realistic enough?:-)