Associating a sequence with pure functions

I often find that I want to insert regular functions into a โ€œboundโ€ sequence. As in this contrived example:

getLine >>= lift (map toUpper) >>= putStrLn 

I need to define the lift function lift :: (a -> b) -> a -> mb to do this job. The problem is that I donโ€™t know such a function, and Hoogle doesn't look either. I find it strange because it makes sense to me.

Now there are probably other ways to make this work, but I like the way the dotless code style allows me to scan the line in one go to figure out what is going on.

 let lift fx = return (fx) in getLine >>= lift (map toUpper) >>= putStrLn 

My question comes down to the following: will I miss something, or why there is no such function as an elevator. My experience at Haskell is still very limited, so I guess most people decide this differently. Can someone explain to me the idiomatic way to resolve this issue.

+8
haskell
source share
2 answers

There are three idiomatic methods.

  • Do not use bind; use the first hit on your google search:

     liftM (map toUpper) getLine >>= putStrLn 

    There are many alternative spellings for liftM , such as fmap or (<$>) .

  • Embed the lift function that you defined:

     getLine >>= return . map toUpper >>= putStrLn 
  • Use the monad laws to merge the last two connectives in option 2:

     getLine >>= putStrLn . map toUpper 
+18
source share

Use a Functor instance in such cases:

 > import Data.Char > import Data.Functor > map toUpper <$> getLine >>= putStrLn foo FOO > 
+3
source share

All Articles