使用cmdargs中的值排序参数

时间:2015-10-18 21:02:25

标签: haskell haskell-cmdargs

此问题是主题的扩展:Ordered arguments with cmdargs

我设法得到了相同类型的参数列表。但是nom,我想有一个带有值的选项列表。像这样:

runhaskell ~/testargs.hs -a 5,6 -b 8,9 -c 4,2 -a 9,3

我尝试用

声明我的数据
data Act = 
    ActA (Double,Double)
  | ActB (Double,Double)
  | ActC (Double,Double)
  deriving (Show, Typeable,  Data, Eq)

但是我收到以下错误:

Couldn't match expected type `Act'
    with actual type `(Double, Double) -> Act'
In the expression: ActA

是否可以检索带有值的参数列表?

1 个答案:

答案 0 :(得分:1)

您可能必须使用较低级别的Explicit api才能执行此操作。

以下是一个示例,说明如何使用Explicit api:

  • 处理 - 帮助
  • 收集多个 -w ... 选项
  • 验证标记的参数
  • 收集所有未命名的参数

用法示例:

prog --help
prog -i=456
prog -w this -w is -w a -w test
prog -i=xyz

程序:

import System.Console.CmdArgs.Explicit
import Data.Char

data MyOptions = Opts { _help    :: Bool
                      , _words   :: [String]
                      , _opt1    :: String
                      , _opt2    :: Int
                      , _unnamed :: [ String ]
                      }
  deriving (Show)

myMode :: Mode MyOptions
myMode = mode "programName" initialOpts  description unnamedArg convertFlags
  where
    initialOpts = Opts False [] "abc" 3 []
    description = "This program does it all."

    unnamedArg = Arg { argValue = updateUnnamed, argType = "<FILE>", argRequire = False }
        where updateUnnamed str opts = Right $ opts { _unnamed = (str : _unnamed opts) }

    updateWord str opts = Right $ opts { _words = (str: _words opts) }
    updateA    str opts = Right $ opts { _opt1 = str }
    updateNum  str opts 
      | not (null str) && all isDigit str = Right $ opts { _opt2 = read str }
      | otherwise                         = Left $ "-i option is not a number: " ++ str

    convertFlags =
       [ flagReq     ["w","word"] updateWord "<WORD>"   "add a word"
       , flagReq     ["a", "bc"]  updateA    "<STRING>" "a string option"
       , flagOpt "0" ["i" ]       updateNum  "<NUMBER>" "a numeric option"
       , flagHelpSimple (\opts -> opts { _help = True })
       ]

main = do
   opts <- processArgs myMode
   print opts
   if _help opts then
       print $ helpText [] HelpFormatDefault myMode
    else
       print opts