简体   繁体   English

在Haskell中对个案声明采取的多项行动

[英]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 晚上的最后一个问题是,我正在构建Haskell程序的主要输入功能,并且必须检查引入的args。

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 issue 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). 这样的库无疑已经存在于Hackage上 ,但这是其中一种情况,其中滚动自己的库可能比学习别人的API容易(肯定会更有趣)。

视图模式在这里可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM