參數處理應該隔離在一個單獨的函數中。 除此之外,很難一概而論,因爲處理參數有很多不同的方式。 這裏有一些類型的簽名,是值得考慮:
exitIfNonempty :: [Arg] -> IO [Arg] -- return args unless empty
processOptions :: [Arg] -> (OptionRecord, [Arg]) -- convert options to record,
-- return remaining args
processOptionsBySideEffect :: [Arg] -> State [Arg] -- update state from options,
-- return remaining args
callFirstArgAsCommand :: [(Name, [Arg] -> IO())] -> [Arg] -> IO()
和一對夫婦實現的草圖(沒有這個代碼已經可以(接近於)編譯器):
exitIfNonempty [] = putStrLen "No arguments; exiting"
exitIfNonempty args = return args
callFirstArgAsCommand commands [] = fail "Missing command name"
callFirstArgAsCommand commands (f:as) =
case lookup f commands in
Just f -> f as
Nothing -> fail (f ++ " is not the name of any command")
我會離開的人發揮你的想象力。
編寫一個函數,將另一個函數拋出到main函數中是否符合我的最佳利益?
是的。此外,你應該建立一個庫的組合器,你可以調用處理命令行參數很容易,爲各種程序。毫無疑問,這樣的庫已經存在於Hackage中,但這是其中一個可能比自己學習別人的API更容易的情況之一(並且它肯定會更有趣)。