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.

import System.Environment
import Control.Monad (forM_)

main :: IO ()
main = do
    -- getArgs provides access to raw command-line arguments.
    -- Note that in Haskell, the program name is not included in the arguments.
    args <- getArgs
    
    -- You can get individual args with normal indexing.
    -- Be careful: this will throw an exception if there aren't enough arguments!
    let thirdArg = args !! 2
    
    putStrLn $ "All arguments: " ++ show args
    putStrLn $ "Third argument: " ++ thirdArg
    
    -- If you want to include the program name, you can use getProgName
    progName <- getProgName
    putStrLn $ "Program name: " ++ progName

To experiment with command-line arguments it’s best to compile the program with ghc first.

$ ghc -o command-line-arguments command-line-arguments.hs
$ ./command-line-arguments a b c d
All arguments: ["a","b","c","d"]
Third argument: c
Program name: command-line-arguments

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.