Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointfree case of

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 ->)?

like image 980
michaelmesser Avatar asked Jan 05 '23 19:01

michaelmesser


1 Answers

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.

like image 120
Daniel Wagner Avatar answered Jan 11 '23 13:01

Daniel Wagner