Multiple actions upon a case statement in Haskell
One last question for the evening, I'm building the main input function of my Haskell program and I have to check for the args that are brought in
so I use
args <- getArgs
case length args of
0 -> putStrLn "No Arguments, exiting"
otherwise -> { other methods here}
Is there an intelligent way of setting up other methods, or is it in my best interest to write a function that the other case is thrown to within the main?
Or is there an even better solution to the issu开发者_运维技巧e of cases. I've just got to take in one name.
args <- getArgs
case length args of
0 -> putStrLn "No Arguments, exiting"
otherwise -> do
other
methods
here
Argument processing should isolated in a separate function. Beyond that it's hard to generalize, because there are so many different ways of handling arguments. Here are some type signatures that are worth considering:
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 ()
And a couple sketches of implementations (none of this code has been anywhere near a compiler):
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")
I'll leave the others to your imagination.
Is it in my best interest to write a function that the other case is thrown to within the main?
Yes. Moreover, you should build up a library of combinators that you can call on to process command-line argument easily, for a variety of programs. Such libraries undoubtedly already exist on Hackage, but this is one of those cases where it may be easier to roll your own than to learn somebody else's API (and it will definitely be more fun).
View Patterns might be helpful here.
精彩评论