Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you supply a default value to a string option in Options.Applicative

Tags:

haskell

How do you indicate a default value via strOption? The documentation for the optparse-applicative library doesn't show how to create a default value for a strOption, e.g.,

data Sample = Sample
  { hello :: String
  , quiet :: Bool }

sample :: Parser Sample
sample = Sample
     <$> strOption
         ( long "hello"
        <> metavar "TARGET"
        <> help "Target for the greeting" )
     <*> switch
         ( long "quiet"
        <> help "Whether to be quiet" )

though it does show how to supply default values for flag options. E.g., Normal is the default in

data Verbosity = Normal | Verbose

flag Normal Verbose
  ( long "verbose"
 <> short 'v'
 <> help "Enable verbose mode"

EDIT

I think I found the answer in the value modifier in Options.Applicative.Builder.

like image 913
dan Avatar asked Mar 07 '14 18:03

dan


2 Answers

This does indeed exist, as value, although it's rather hard to find in the documentation.

Example:

strOption  ( long "some-opt"
          <> value "default value"
          <> metavar "SOMEOPT"
          <> help "an option demonstrating the use of `value'" )
like image 73
Rein Henrichs Avatar answered Oct 06 '22 11:10

Rein Henrichs


Quoting the readme:

Parsers are instances of both Applicative and Alternative

Which means you should just be able to specify default values like this:

someOption <|> pure "thisIsUsedIfSomeOptionWasn'tPassed"

You could create a default combinator like this

 defaultValue :: Alternative f => a -> f a -> f a
 defaultValue = flip (<|>) . pure

And use it like this

 optionWithDefault :: Parser String
 optionWithDefault = defaultValue "defaultValue" option

I'd be surprised if that didn't exist already in some form though.

like image 35
Cubic Avatar answered Oct 06 '22 10:10

Cubic