Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing monad value before assignment

Tags:

syntax

haskell

Is it possible to make those two lines one line:

main = do line <- getLine 
    let result = words line

what I mean is something like non monadic code

result = words getLine

which -- in my opinion -- would improve readability.

like image 613
Trismegistos Avatar asked Jan 25 '12 18:01

Trismegistos


1 Answers

Try this: result <- fmap words getLine

fmap takes a function with a type like a -> b and turns it into f a -> f b for anything that's an instance of Functor, which should include all Monad instances.

There's an equivalent function called liftM that's specific to Monad, for murky historical reasons. You might need to use that instead in some cases, but for standard monads like IO you can stick with fmap.

You can also import Data.Functor or Control.Applicative to get a nice operator version of fmap, so you could write words <$> getLine instead, which often looks prettier.

like image 71
C. A. McCann Avatar answered Nov 11 '22 01:11

C. A. McCann