do you know a relatable scenario where one would u...
# arrow
s
do you know a relatable scenario where one would use ap on an Either
d
Suppose you have a curried function of type
(A) -> (B) -> C
. Passing that to
Either<X, A>#map
would return a value of type
Either<X, (B) -> C>
. If you want to get an
Either<X, C>
out of it, you can it into
Either<X, B>#ap
. This is arbitrarily chainable too. Example:
Copy code
fun makePerson(name: String): (Int) => Person = { age: Int -> Person(name,age) }
val name: Either<X,String> = /*...*/
val age: Either<X,Int> = /*...*/ 
val person: Either<X,Person> = age.ap(name.map(::makePerson))
Applicative#map
makes this syntax much cleaner, and is implemented using
ap
.
🙏 1
s
Thanks, will (attempt to) digest that
d
ap
gets a lot of use in something like Haskell (where
map
and
ap
are called
<$>
and
<*>
, respectively) because you can use that syntax to go
Person <$> name <*> age
(equivalent to
Applicative#ap(Functor#map)
in Arrow), which, once you understand the operators, is a little nicer than
liftA2 Person $ name age
(equivalent to
Applicative#map
in Kotlin).
👍🏼 1
s
Thanks. It's a little clearer now
Copy code
val output = fn1.map({ it(2) })
    val output2 = Some(2).ap(fn1)
    val output3 = Some(2).flatMap({ v -> fn1.map({ it(v) }) })
    println(output)
    println(output2)
    println(output3)
What happens if fn1 return Some("Matt" + i) is there like a flatMap version of ap
d
Yes, for monads
In fact the default implementation of
ap
for monads uses
flatMap