Environment Variables in Idris

Our first example demonstrates how to work with environment variables in Idris. Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.

import System
import Data.String

main : IO ()
main = do
    -- To set a key/value pair, use `setEnv`. To get a
    -- value for a key, use `getEnv`. This will return
    -- Maybe String, where Nothing represents an absent key.
    setEnv "FOO" "1"
    putStrLn $ "FOO: " ++ fromMaybe "" !(getEnv "FOO")
    putStrLn $ "BAR: " ++ fromMaybe "" !(getEnv "BAR")

    -- Use `getEnvironment` to list all key/value pairs in the
    -- environment. This returns a list of (String, String) pairs.
    -- Here we print all the keys.
    putStrLn ""
    env <- getEnvironment
    traverse_ (\(k, _) -> putStrLn k) env

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ idris -o env_vars env_vars.idr
$ ./env_vars
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 ./env_vars
FOO: 1
BAR: 2
...

In Idris, we use the System module to interact with environment variables. The setEnv function is used to set environment variables, while getEnv is used to retrieve them. Unlike in some other languages, getEnv returns a Maybe String, where Nothing represents an absent key.

To list all environment variables, we use the getEnvironment function, which returns a list of key-value pairs. We then use traverse_ to iterate over this list and print each key.

This example demonstrates how to manipulate environment variables in Idris, providing a foundation for more complex configuration management in your programs.