我正在开发一个供个人使用的家庭作业管理器,使用 Haskell 开发它。作为开始,我制作了以下代码来解析命令行参数,这些代码我以后应该可以通过添加到dispatch
. 函数本身是用于测试目的的虚拟对象。然而,我确实觉得这段代码可以变得更简单,更安全,尽管我不知道怎么做。代码是这样的:
module Main where
import System.Environment
main = getArgs >>= parse
parse :: [String] -> IO ()
parse [] = usage
parse (file:mode:[]) = if mode == "list"
then list file
else case lookup mode dispatch of
Just _ -> putStrLn "That mode requires arguments" >> usage
Nothing -> putStrLn "Please supply a valid mode" >> usage
parse (file:mode:args) = case lookup mode dispatch of
Nothing -> do case lookup file dispatch of
Just _ -> putStrLn "Please supply a data file"
Nothing -> putStrLn "Please supply a valid mode"
usage
Just fun -> fun file args
parse (file:[]) = case lookup file dispatch of
Just _ -> putStrLn "Please supply a datafile" >> usage
Nothing -> list file
usage :: IO ()
usage = mapM_ putStrLn helptext
helptext :: [String]
helptext = ["Homework manager by Marcus Medom Ryding <mrok4a@gmail.com>"
,"Copyright 2013, licensed under BSD3"
,"Usage: homework filepath [mode] [arguments]"]
dispatch :: [(String, String -> [String] -> IO ())]
dispatch = [("new",new)]
new :: String -> [String] -> IO ()
new file args = putStrLn ("NEW: " ++ file) >> mapM_ putStrLn args
list :: String -> IO ()
list file = putStrLn ("LIST: " ++ file)