Published on December 30, 2016; tags: Haskell
When I need to write a command-line program in Haskell, I invariably pick Paolo Capriotti’s optparse-applicative library.
Unfortunately, the minimal working example is complicated enough that I cannot reproduce it from memory, and the example in the README is very different from the style I prefer.
So I decided to put up a template here for a program using optparse-applicative. I am going to copy it into all of my future projects, and you are welcome to do so, too.
import Options.Applicative import Control.Monad (join) import Data.Monoid ((<>)) main :: IO () main = join . customExecParser (prefs showHelpOnError) $ info (helper <*> parser) ( fullDesc <> header "General program title/description" <> progDesc "What does this thing do?" ) where parser :: Parser (IO ()) parser = work <$> strOption ( long "string_param" <> short 's' <> metavar "STRING" <> help "string parameter" ) <*> option auto ( long "number_param" <> short 'n' <> metavar "NUMBER" <> help "number parameter" <> value 1 <> showDefault ) work :: String -> Int -> IO () work _ _ = return ()