TAGS :Viewed: 2 - Published at: a few seconds ago

[ List of Environment Variables to Dictionary with Values - Idiomatic F# ]

What is the idiomatic way to take a F# list of string like


and convert that to a Dictionary where the words above are the keys and the corresponding Environment Variable is the value.

Should all that be done in a one-liner or piped expression? I am missing the FP background to know how to go from list to Dictionary. What is the most idiomatic way to do this in F#?

Answer 1

Environment.GetEnvironmentVariable and the dict function should do the work :

let env =
  |> Seq.map (fun var -> var, Environment.GetEnvironmentVariable var)
  |> dict

Answer 2

Alternatively to @Sehnsucht's answer:

Environment.GetEnvironmentVariables() already returns a dictionary, so if you don't want to restrict yourself to the names you specified you could just say:

let d = Environment.GetEnvironmentVariables()
printfn "%s" d.["BUILD_NUMBER"]

If you only ever access d.[xxxx] in your code (where xxxx is one of the strings you specify in your question), there's arguably no reason to make another dictionary just for those names.