Environment Variables in Standard ML

Our program demonstrates how to work with environment variables in Standard ML. Environment variables are a universal mechanism for conveying configuration information to programs.

(* Import necessary modules *)
structure OS = OS;
structure String = String;

(* Function to set environment variable *)
fun setenv (name, value) =
    OS.Process.setEnv (name, value)

(* Function to get environment variable *)
fun getenv name =
    case OS.Process.getEnv name of
        SOME value => value
      | NONE => ""

(* Main function *)
fun main () =
    let
        (* Set a key/value pair *)
        val _ = setenv ("FOO", "1")
        
        (* Get and print values *)
        val _ = print ("FOO: " ^ getenv "FOO" ^ "\n")
        val _ = print ("BAR: " ^ getenv "BAR" ^ "\n")
        
        (* Print all environment variables *)
        val _ = print "\n"
        val envList = OS.Process.getEnv
        fun printEnv [] = ()
          | printEnv ((name, _)::rest) =
            (print (name ^ "\n"); printEnv rest)
    in
        printEnv (envList ())
    end

(* Run the main function *)
val _ = main ()

To set a key/value pair, we use the setenv function. To get a value for a key, we use the getenv function. This will return an empty string if the key isn’t present in the environment.

We use OS.Process.getEnv to list all key/value pairs in the environment. This returns a list of strings in the form (KEY, value). Here we print all the keys.

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

$ sml environment_variables.sml
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

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

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

$ export BAR=2 && sml environment_variables.sml
FOO: 1
BAR: 2
...

Note that Standard ML doesn’t have built-in functions for environment variables like Go does. We’ve created wrapper functions to mimic the behavior of Go’s os.Setenv and os.Getenv. Also, Standard ML doesn’t have a direct equivalent to Go’s strings.SplitN, so we’ve adjusted our approach to printing environment variables accordingly.