I want to write a function to read an Int
without do
notation. It works (see below), but I was wondering if it the bit around readMaybe
can be written in point free form (or cleaned up a bit in some other way)?
main :: IO ()
main = getLine >>= (\x -> return $ (readMaybe x :: Maybe Int)) >>= print
Step 1: Replace the lambda with its pointfree equivalent:
Step 2: Replace
m >>= return . f
withf <$> m
:Step 3: Replace
f <$> m >>= g
withm >>= g . f
:Step 4: Use a type application instead of writing out a long, awkward type:
As an alternative to using
<$>
in steps 2 and 3, you can accomplish the same with just the monad laws, like this (picking up after step 1):Replace
m >>= f >>= g
withm >>= \x -> f x >>= g
(associativity):Simplify the
.
away:Replace
return x >>= f
withf x
(left identity):Now just replace that new lambda with its pointfree equivalent, and you end up in the exact same place as step 3.