I'm learning functional programming and have some (maybe obvious, but not for me :) ) question about monad. Every monad is an applicative functor. Applicative functor in turn can be defined as a higher-kinded type as follows (pure
method omitted):
trait ApplicativeFunctor[F[_]]{
def ap[A](fa: F[A])(f: F[A => B]): F[B]
}
As far as I understand this typeclass means that we can take two values of F[A]
, F[B]
and a function (A, B) => C
and construct F[C]
.
This property enables us to construct the list reversing function:
def reverseApList[F[_]: ApplicativeFunctor, A](lst: List[F[A]]): F[List[A]]
Let we have
trait SomeType[A]
Now consider
type MyFree[A] = Free[SomeType, A]
val nt: NaturalTransformation[SomeType, Id]
val lst: List[MyFree[Int]]
QUESTION: Why are lst.map(_.foldMap(nt))
and reverseApList(lst).foldMap(nt)
the same? Is it following from applicative functor laws or there is another reason? Can you please explain?
C
. What you described is calledmap2
, notap
. Furthermore, I don't quite get what's going on withreverse
. Are you really reversing anything, or is it a typo and you meant "traverse"? – AirboatApply
in scalaz. This is defined asap
. I just said thatmap2
can be gotten fromap
. By reversing I meant makingF[List[A]]
fromList[F[A]]
. Such order reversing can only be done for application functors, not just functors... – Coauthorapply2
, notmap2
:) – CoauthorApplicative.sequence
btw. – Coauthorapply2
in scalaz. A similar function is called map2 in cats , and also in Bjarnason/Chiusano , if I'm not confusing anything. – Airboat