Haskell: Parsing command line arguments

后端 未结 4 1047
耶瑟儿~
耶瑟儿~ 2021-02-02 09:14

This more of a style question, rather than a how to.

So I\'ve got a program that needs two command line arguments: a string and an integer.

I implemented it this

4条回答
  •  醉酒成梦
    2021-02-02 10:00

    These days, I'm a big fan of optparse-generic for parsing command line arguments:

    • it lets you parse arguments (not just options)
    • it lets you parse options (not just arguments)
    • you can annotate the arguments to provide a useful help
    • but you don't have to

    As your program matures, you may want to come up with a complete help, and a well-annotated options data type, which options-generic is great at. But it's also great at parsing lists and tuples without any annotation at all, so you can hit the ground running:

    For example

    {-# LANGUAGE OverloadedStrings #-}
    module Main where
    
    import Options.Generic
    
    main :: IO ()
    main = do
      (n, c) <- getRecord "Example program"
      putStrLn $ replicate n c
    

    Runs as:

    $ ./OptparseGenericExample
    Missing: INT CHAR
    
    Usage: OptparseGenericExample INT CHAR
    $ ./OptparseGenericExample 5 c
    ccccc
    

提交回复
热议问题