2

i will determine the program mode from the arguments count (without flags / 'subparser' & 'command') but without success.

ghci session

main% stack ghci optparse-applicative
Configuring GHCi with the following packages: 
GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
λ: :load Main.hs 
[1 of 1] Compiling Main             ( Main.hs, interpreted )
Ok, modules loaded: Main.
λ: :main -v
v 0.0.1
λ: :main a
mode 1 with a: a
λ: :main a b
Usage: <interactive> (-v | a | a b)
*** Exception: ExitFailure 1

with :main a b i expected mode 2 with a: a and b: b as the result.

what did i miss? thanks!


Main.hs

module Main where

import           Options.Applicative

data AppArgs = ShowVersion
             | Mode1 {
                 a :: String
               }
             | Mode2 {
                 a :: String
               , b :: String
               }


main :: IO ()
main = execParser opts >>= run
    where opts = info (helper <*> appArgs)
                 ( fullDesc
                 <> header "example")


appArgs :: Parser AppArgs
appArgs = flag' ShowVersion (short 'v')
       <|> Mode1 <$> strArgument (metavar "a")
       <|> Mode2 <$> strArgument (metavar "a") <*> strArgument (metavar "b")


run :: AppArgs -> IO ()
run ShowVersion = putStrLn "v 0.0.1"
run (Mode1 a)   = putStrLn $ "mode 1 with a: " ++ a
run (Mode2 a b) = putStrLn $ "mode 2 with a: " ++ a ++ " and b: " ++ b
nponeccop
  • 13,527
  • 1
  • 44
  • 106
j-keck
  • 1,021
  • 1
  • 7
  • 13
  • 2
    See the [answer](http://stackoverflow.com/a/31955871/71116) that the author of optparse-applicative gave to a similar question. It seems that the `Alternative` instance of `Parser` does not do backtracking – Michael Steele Dec 16 '15 at 04:05

0 Answers0