Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Monadic construct within lambda function

Tags:

haskell

I have this snippet of a function:

mapM (\x -> do t' <- t; return $ strSwop "if0" ("if" ++ show x) t') [0..(n-1)]

With

strSwop :: String -> String -> String -> String
t :: IO String

It works as expected but I don't like the IO construct withing the lambda. How can it be written differently? I come out of the monad just to be wrapped again next line. Feels ugly.

If I do it this way:

mapM (\x -> t >>= strSwop "if0" ("if" ++ show x) t) [0..(n-1)]

It complains (obviously) about the return signature of strSwop :( strSwop is just a string replacement function. Is there a way to correctly write this? Thanks.

-- EDIT --

Just figured it out ...

Works out:

mapM (\x -> liftM (strSwop "if0" ("if" ++ show x)) t) [0..(n-1)]
like image 663
r.sendecky Avatar asked Apr 13 '26 06:04

r.sendecky


1 Answers

I would suggest liftM or <$>

import Control.Applicative
mapM (\x -> strSwop "if0" ("if" ++ show x) <$> t) [0..(n-1)]
like image 55
Chris Kuklewicz Avatar answered Apr 16 '26 18:04

Chris Kuklewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!