I would like to use the optparse-applicative package to add command line arguments to my program.
The program requires different types of parameters (String
and Int
). To keep it simple, I would like to only have one data type to hold all my settings like this:
data Configuration = Configuration
{ foo :: String
, bar :: Int
}
I found one way here to do this. But unfortunately it seems that the functions have changed.
Here is a minimal (not) working example of what I would like to do:
module Main where
import Options.Applicative
import Control.Monad.Trans.Reader
data Configuration = Configuration
{ foo :: String
, bar :: Int
}
configuration :: Parser Configuration
configuration = Configuration
<$> strOption
( long "foo"
<> metavar "ARG1"
)
<*> option
( long "bar"
<> metavar "ARG2"
)
main :: IO ()
main = do
config <- execParser (info configuration fullDesc)
putStrLn (show (bar config) ++ foo config)
Is there a simple way to do this or do I have to implement a intOption
similar to the strOption
?
All you need to do is tell option to use the auto reader, as in this fragment of code:
configuration :: Parser Configuration
configuration = Configuration
<$> strOption
( long "foo"
<> metavar "ARG1"
)
<*> option auto
( long "bar"
<> metavar "ARG2"
)
The difference between strOption and option, is that strOption assumes a String return type, while option can be configured to use custom readers. The auto reader assumes a Read instance for the return type.
There is good documentation in the OptParse applicative Hackage page.
I hope this helps.
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