Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Int with the optparse-applicative inside a data constructor?

Tags:

haskell

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?

like image 622
Gerrit Avatar asked Oct 16 '25 19:10

Gerrit


1 Answers

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.

like image 82
fgv Avatar answered Oct 18 '25 08:10

fgv