I need to extract function from monad, which is possible for any monad:
def extractf[A, B, F[_]: Monad](ff: F[A ⇒ F[B]]): A ⇒ F[B] = a ⇒ {
Monad[F].bind(ff)(f ⇒ f(a))
}
I could not find such function neither in scalaz nor in hoogle.
I tried to achieve the same using sequencing on Kleisli (the idea was to do sequence . join ) or unlifting, but that was becoming overcomplicated so I stopped.
My question is - did I just fail finding this function or nobody uses it for any reason (if so, then how to achieve the same goal)?
Thanks!
Applicative's pure is heading the chain, lifting A into F[A] like Haskell's return. Then we use apF from Apply, a weakened variant of Applicative, to substitute argument into function within functor, obtaining F[F[B]] from F[A] and F[A => F[B]]. Finally, join from the Bind typeclass, the second component of monad, flattens F[F[B]] into F[B]. What remains is to call the combined function on the value of A. Note that Monad is indeed Applicative and Bind, and Applicative is also Apply, so one can replace the use of all that granular typeclasses with Monad.
While that works, it can be inconvenient in some cases because of syntax quirk. User is forced to explicitly pass an instance of monad to the implicit parameter generated from context bound or save function into val before its application to an argument. Equivalent function would be: