[Haskell-beginners] How can I lift my function taking a function to a Monad?

Simon Peter Nicholls simon at mintsource.org
Thu Dec 10 12:43:45 UTC 2015


Hi All,

Can anyone help me lift a function that takes a function, so it can be 
used in a Monad?

The function I am given looks like "((b -> b) -> a -> a)", and viewing 
the definition of liftM2, it's almost what I need:

liftM2 :: (Monad m) => (a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 f m1 m2 = do
  x1 <- m1
  x2 <- m2
  return (f x1 x2)

but I get the error:

   Expected type: (m b -> m b) -> m a -> m a
      Actual type: m (b -> b) -> m a -> m a

which makes sense, as liftM2 just wraps my function arg, whereas the 
function itself needs to operate on monadic values. So I figure I need:

neededLift :: (Monad m) => ((b -> b) -> a -> a) -> (m b -> m b) -> m a 
-> m a

Despite a rough appreciation of how liftM2 works ("unpack" desired 
monadic versions of the args, apply the function, then return to put 
result back in the Monad), my mind keeps hazing over regarding the 
changes I need to make in this case. I've tried implementing neededLift 
by composing other functions, and also by manual Monad wrangling, but 
the intuitive leap remains elusive.

I posted the specific problem over at SO 
(http://stackoverflow.com/questions/34152747/how-can-i-lift-an-fclabels-lens-to-a-monad), 
but I think the specifics may be clouding what is probably a 
straightforward problem.

Cheers,
Si


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151210/e7218af4/attachment.html>


More information about the Beginners mailing list