類型的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