For a monad M
, Is it possible to turn A => M[B]
into M[A => B]
?
I've tried following the types to no avail, which makes me think it's not possible, but I thought I'd ask anyway. Also, searching Hoogle for a -> m b -> m (a -> b)
didn't return anything, so I'm not holding out much luck.
No.
For example,
Option
is a monad, but the function(A => Option[B]) => Option[A => B]
has no meaningful implementation:What do you put instead of
???
?Some
?Some
of what then? OrNone
?In Practice
No, it can not be done, at least not in a meaningful way.
Consider this Haskell code
This takes
n
first, prints it (IO performed here), then reads a line from the user.Assume we had an hypothetical
transform :: (a -> IO b) -> IO (a -> b)
. Then as a mental experiment, consider:The above has to do all the IO in advance, before knowing
n
, and then return a pure function. This can not be equivalent to the code above.To stress the point, consider this nonsense code below:
Magically,
action'
should know in advance what the user is going to type next! A session would look asThis requires a time machine, so it can not be done.
In Theory
No, it can not be done. The argument is similar to the one I gave to a similar question.
Assume by contradiction
transform :: forall m a b. Monad m => (a -> m b) -> m (a -> b)
exists. Specializem
to the continuation monad((_ -> r) -> r)
(I omit the newtype wrapper).Specialize
r=a
:Apply:
By the Curry-Howard isomorphism, the following is an intuitionistic tautology
but this is Peirce's Law, which is not provable in intuitionistic logic. Contradiction.
The other replies have nicely illustrated that in general it is not possible to implement a function from
a -> m b
tom (a -> b)
for any monadm
. However, there are specific monads where it is quite possible to implement this function. One example is the reader monad: