Command Line Arguments in Idris

Command-line arguments are a common way to parameterize execution of programs. For example, idris hello.idr -o hello uses hello.idr and -o hello arguments to the idris program.

module Main

import System
import System.Info

main : IO ()
main = do
    -- getArgs provides access to raw command-line arguments.
    -- Note that the first value in this list is the path to the program.
    args <- getArgs
    
    let argsWithProg = args
    let argsWithoutProg = tail args

    -- You can get individual args with normal indexing.
    -- Be cautious: this might fail if there aren't enough arguments.
    let arg = case (index' 3 args) of
                Just a -> a
                Nothing -> "Not enough arguments"

    putStrLn $ show argsWithProg
    putStrLn $ show argsWithoutProg
    putStrLn arg

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

$ idris -o command-line-arguments command-line-arguments.idr
$ ./command-line-arguments a b c d
["./command-line-arguments", "a", "b", "c", "d"]
["a", "b", "c", "d"]
d

In Idris, we use the System module to access command-line arguments. The getArgs function returns a list of strings containing the program name and all command-line arguments.

Note that Idris uses index' for safe indexing, which returns a Maybe type. We’ve added a simple case expression to handle the possibility of not having enough arguments.

Next, we’ll look at more advanced command-line processing with options parsing libraries available in Idris.