I have this code:
import Control.Lens
import Control.Monad
import Control.Arrow
import Text.Read
... IO (Maybe String) ...
>>= \m -> case m of
Just x -> putStrLn x
Nothing -> putStrLn "Error"
Is it possible to make it pointfree (get rid of the \m ->
)?
There are several ways. In this particular case:
putStrLn . fromMaybe "Error"
But this is a pretty special case. Slightly less special would be to use the Maybe
catamorphism:
maybe (putStrLn "Error") putStrLn
Many types in Haskell come with a similar catamorphism that can be used to avoid case
. But the most general case is to use the special language extension known as LambdaCase
, which lets you write
\case
Just x -> putStrLn x
Nothing -> putStrLn "Error"
Unlike fromMaybe
(which is special to Maybe
and the regularity of the cases used here) or the catamorphism (which is special to types that provide one), this can be used to anonymize any pattern-matching lambda.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With