2010-05-16 40 views
1

最後一個問題的晚上,我建立我的Haskell程序的主要輸入功能,我要檢查,所以我用多個動作

所帶來

的ARGS

args <- getArgs 
case length args of 
    0 -> putStrLn "No Arguments, exiting" 
    otherwise -> { other methods here} 

是否有一種智能的方法來設置其他方法,或者是否有我寫的函數,而另一個函數被拋出到主函數中是否有利於我?

還是有更好的解決方案的問題。我只需要帶上一個名字。

回答

2

參數處理應該隔離在一個單獨的函數中。 除此之外,很難一概而論,因爲處理參數有很多不同的方式。 這裏有一些類型的簽名,是值得考慮:

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更容易的情況之一(並且它肯定會更有趣)。

8
args <- getArgs 
case length args of 
    0 -> putStrLn "No Arguments, exiting" 
    otherwise -> do 
     other 
     methods 
     here