27

optparse-applicativeを使用して a を解析しようとしてMaybe Stringいますが、 を処理する方法がどこにも見つかりませんMaybeNothing私が見つけた唯一のことは、デフォルト値を追加することですが、ユーザーが代わりにオプションを提供しなかった場合は本当に必要です""。これを達成する方法はありますか?

作業コードの例を次に示します。

import Options.Applicative

data Config = Config
    { cIn :: String
    , cOut :: String
    } deriving Show

configParser :: Parser Config
configParser = Config
    <$> strOption (long "in" <> short 'i')
    <*> strOption (long "out" <> short 'o')


main :: IO ()
main = do
    conf <- execParser (info configParser fullDesc)
    print conf

ただし、パラメーターをオプションにして、 inMaybe Stringの代わりに使用したいと思います。StringConfig

data Config = Config
    { cIn :: Maybe String
    , cOut :: Maybe String
    } deriving Show
4

1 に答える 1

35

optparse-applicativeREADMEの次の一節を参照してください。

パーサーは と の両方のインスタンスでApplicativeあり、とAlternativeのような汎用コンビネータと連携します。たとえば、オプションが指定されていない場合に失敗するのではなく、オプションを返すようにするには、コンビネータを次のように使用できます。manysomeNothingoptionalControl.Applicative

optional $ strOption
   ( long "output"
  <> metavar "DIRECTORY" )

optionalしたがって、コンビネータを の結果に適用するだけですstrOption

import Options.Applicative

data Config = Config
    { cIn  :: Maybe String
    , cOut :: Maybe String
    } deriving Show

configParser :: Parser Config
configParser = Config
    <$> (optional $ strOption $ long "in" <> short 'i')
    <*> (optional $ strOption $ long "out" <> short 'o')

main :: IO ()
main = do
    conf <- execParser (info configParser fullDesc)
    print conf

コマンドラインでのテスト:

$ main --in foo -o bar
Config {cIn = Just "foo", cOut = Just "bar"}
$ main -i foo
Config {cIn = Just "foo", cOut = Nothing}
于 2015-09-06T10:57:55.160 に答える