类型的option
是:
ReadM
,在转向,是“ReaderT字符串以外的新类型”,由选项阅读器使用“。由于option
使用ReaderT
引擎盖下,当你的ReadM
像你这样在这里Applicative
情况下使用它...
ROI <$> auto <*> auto <*> auto <*> auto
...相同,整体而言,输入字符串被提供给每个四个auto
解析器,因为这就是读者/函数应用实例的工作方式。
如果您希望将由空格分隔的值分解为单个ROI
,则需要编写自定义分析程序。这是一个不太特别的尝试,围绕eitherReader
。请注意,这将要求值位于引号(--roi "1 2 3 4"
)内,以便将它们作为单个字符串引入。 Cubic的答案提出了一种替代方法,它使用逗号分隔值(--roi 1,2,3,4
)。
import Text.Read (readEither)
-- etc.
roi :: Parser (Maybe ROI)
roi = optional
$ option (eitherReader $ \inp -> case traverse readEither (words inp) of
Right [x, y, z, w] -> Right (ROI x y z w)
Right _ -> Left "ROI requires exactly 4 values"
Left _ -> Left "ROI requires integer values")
$ long "roi" <> metavar "ROI" <> help "Only process selected region of interest"
成功和失败的模式:
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 3 4"]
Success (Just (ROI 1 2 3 4))
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 3"]
Failure (ParserFailure (option --roi: ROI requires exactly 4 values
Usage: <program> [--roi ROI],ExitFailure 1,80))
GHCi> execParserPure defaultPrefs (info roi mempty) ["--roi","1 2 foo 4"]
Failure (ParserFailure (option --roi: ROI requires integer values
Usage: <program> [--roi ROI],ExitFailure 1,80))
我已经编辑我的回答澄清'--roi 1 2 3 4'不会与任何这里的方法的工作 - 最接近你可以得到像'--roi 1,2,3,4'这样的东西,就像在Cubic的答案中一样。 – duplode