我同意optparse-applicative
包是非常好的。真棒! 讓我給一個最新的例子。
該程序需要一個字符串和一個整數n作爲參數,返回字符串複製n次,並且它有一個反轉字符串的標誌。
-- file: repstring.hs
import Options.Applicative
import Data.Monoid ((<>))
data Sample = Sample
{ string :: String
, n :: Int
, flip :: Bool }
replicateString :: Sample -> IO()
replicateString (Sample string n flip) =
do
if not flip then putStrLn repstring else putStrLn $ reverse repstring
where repstring = foldr (++) "" $ replicate n string
sample :: Parser Sample
sample = Sample
<$> argument str
(metavar "STRING"
<> help "String to replicate")
<*> argument auto
(metavar "INTEGER"
<> help "Number of replicates")
<*> switch
(long "flip"
<> short 'f'
<> help "Whether to reverse the string")
main :: IO()
main = execParser opts >>= replicateString
where
opts = info (helper <*> sample)
(fullDesc
<> progDesc "Replicate a string"
<> header "repstring - an example of the optparse-applicative package")
一旦文件被編譯(與ghc
照常):
$ ./repstring --help
repstring - an example of the optparse-applicative package
Usage: repstring STRING INTEGER [-f|--flip]
Replicate a string
Available options:
-h,--help Show this help text
STRING String to replicate
INTEGER Number of replicates
-f,--flip Whether to reverse the string
$ ./repstring "hi" 3
hihihi
$ ./repstring "hi" 3 -f
ihihih
現在,假設你想要一個可選的參數,名稱追加字符串的結尾:
-- file: repstring2.hs
import Options.Applicative
import Data.Monoid ((<>))
import Data.Maybe (fromJust, isJust)
data Sample = Sample
{ string :: String
, n :: Int
, flip :: Bool
, name :: Maybe String }
replicateString :: Sample -> IO()
replicateString (Sample string n flip maybeName) =
do
if not flip then putStrLn $ repstring ++ name else putStrLn $ reverse repstring ++ name
where repstring = foldr (++) "" $ replicate n string
name = if isJust maybeName then fromJust maybeName else ""
sample :: Parser Sample
sample = Sample
<$> argument str
(metavar "STRING"
<> help "String to replicate")
<*> argument auto
(metavar "INTEGER"
<> help "Number of replicates")
<*> switch
(long "flip"
<> short 'f'
<> help "Whether to reverse the string")
<*> (optional $ strOption
(metavar "NAME"
<> long "append"
<> short 'a'
<> help "Append name"))
編譯並玩得開心:
$ ./repstring2 "hi" 3 -f -a rampion
ihihihrampion
谷歌是你的朋友!下面是關於Haskell命令行參數的一個很好的說明: http://leiffrenzel.de/papers/commandline-options-in-haskell.html – Sanjamal 2011-12-22 22:16:43
@Sanjamal:雖然這並不簡化對* arguments *的解析,只是選擇。 – ehird 2011-12-22 22:18:27
你也可以使用'LambdaCase'給你'getArgs >> = \ case ...'而不是'args < - getArgs; ...' – rampion 2017-05-09 15:32:41