How to use Int with optparse application inside a data constructor?

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 have only one datatype to store all my settings:

data Configuration = Configuration
                    { foo :: String
                    , bar :: Int
                    }

      

I found one way here to do this. But unfortunately, it seems that the features 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 an easy way to do this or do I need to implement a intOption

similar one strOption

?

+3


source to share


1 answer


All you need to do is indicate the ability to use auto-update, as in this code snippet:

configuration :: Parser Configuration
configuration = Configuration
    <$> strOption
        ( long "foo"
        <> metavar "ARG1"
        )
    <*> option auto
        ( long "bar"
        <> metavar "ARG2"
        )

      

The difference between strOption and an option is that strOption takes a return type of String, whereas an option can be configured to use custom readers. Autodevice takes an instance of Read for the return type.



There is good documentation in the OptParse application application .

Hope this helps.

+5


source







All Articles