Command Line Arguments in Haskell
Command-line arguments are a common way to parameterize execution of programs. For example, runhaskell hello.hs
uses runhaskell
and hello.hs
arguments to run a Haskell program.
To experiment with command-line arguments it’s best to compile the program with ghc
first.
In Haskell, command-line arguments are accessed using the getArgs
function from the System.Environment
module. Unlike in some other languages, the program name is not included in the list of arguments by default. If you need the program name, you can use the getProgName
function.
The !!
operator is used for list indexing in Haskell, but be cautious as it will throw an exception if the index is out of bounds. In a real-world application, you might want to use safer methods of accessing arguments, such as pattern matching or the safe
package.
Next, we’ll look at more advanced command-line processing with option parsing libraries like optparse-applicative
.