Scala,Cats, usage of `ap`

Viewed 239

I am going trough the https://www.scala-exercises.org/ for Cats. I guess that I understand what does Apply.ap. But I cannot see any usage of that.

What is the difference between:

Apply[Option].map(Some(1))(intToString)

and

Apply[Option].ap(Some(intToString))(Some(1))

Can someone explain a bit more or point me to more explanations ?

1 Answers

There is no difference between

Apply[Option].map(Some(1))(intToString)

and

Apply[Option].ap(Some(intToString))(Some(1))

Both are Some("1").

But there is a big difference between map and ap.

map comes from the type class Functor and has a signature

def map[A, B](fa: F[A])(f: A => B): F[B]

ap comes from the type class Apply and has a signature

def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]

So map applies a function A => B to a value in a context F[A] while ap applies a function F[A => B] in a context to a value in a context F[A].

For example

Apply[List].map(List(1, 2))(intToString)

is List("1", "2") while

Apply[List].ap(List(intToString, (i: Int) => intToString(i) + "a"))(List(1, 2))

is List("1", "2", "1a", "2a").

Apply[Option].map(fx)(f) can be None only when fx is None while Apply[Option].ap(ff)(fx) can be None when fx is None or ff is None.

Related