I’m confused about what is `Functor`, `Applicative...
# arrow
f
I’m confused about what is
Functor
,
Applicative
and
Monad
. How do you explain these terms for a programmer with OOP background/terminology?
I found that
Functor
is everything that could be mapped. By these definition we can say that all iterables are `Functor`s.
p
Applicative means it has a factory and can have multiple instances running independently. If you can create an Iterable, an Option, or a List from a value with a factory, that's easily an Applicative.
List.just(1) // List<Int>
Option.just(1) // Some<Int>
Sequence { yield(1) } // Sequence<Int>
Running independently means that you can have two options that don't depend on each other, and have a result only if both are Some. Or merging two lists together.
map(listA, listB) { a, b -> a to B } // List<Tuple<A, B>>
map(hasName, hasAddress) { name, address -> User(name, address) }
Monad means that you have two or more elements that depend on each other, and have to run sequentially. For example, making a list out of each of the elements of another list. Or an Option that's created only if a previous Option has succeeded. That's why flatMap is sometimes called andThen.
a.andThen { B(it) }
list.map { listOf(it, it) }
// List<List<Int>>
list.flatMap { listOf(it, it) }
// List<Int>
f
Everything capable of applying
flatMap
on it is a
Monad
, yeah?
p
yes
there are some tests it has to pass too, so all Monad instances behave the same
f
I got the
Functor
and
Monad
. But need a simpler explanation to understand
Applicative
.
p
Factory is understandable, I take
that it has a constructor. I know it sounds silly, but having a constructor function is key for the other typeclasses
imagine that interfaces had the possibility of describing what the constructor will look like
Copy code
interface FromString<T> {
  constructor T(a: String)
}
class Bla(s: String): FromString<Bla>
that's not possible today, so you have to define a factory function outside of the class...which luckily is how all typeclasses are defined
👍 1
class Bla(s: String) { companion object: FromString<Bla> { override fun construct(s: String): Bla = Bla(s) } }
👍 1
d
Applicative
generalizes
Functor.map
to polyadic functions
Functor lets you turn
(A) -> B
into
(F<A>) -> F<B>
👍 1
While applicative lets you turn
(A,B,C,...) -> Z
into
(F<A>,F<B>,F<C>,...) -> F<Z>
👍 1