When working with associative arrays in Python, I wonder how these work in other languages. Especially functional programming languages. For example, one would create a dictionary, as associative arrays are called in Python, as follows.
>>> dic = {'foo': 42, 'bar': 43}
>>> dic
{'foo': 42, 'bar': 43}
Now how does that work in, let’s say Haskell? Well, it’s not that difficult.
Prelude> let dic = [("foo", 42), ("bar", 43)]
Prelude> dic
[("foo",42),("bar",43)]
Looks pretty similar, huh? I had expected something more complicated. Well, this is the most simple case, of course. However, good to know that the simple case can be written in a simple way. Now how does the creation of associative arrays look in F#? First, they are called maps here. And one creates them as follows.
> let dic = [ "foo", 42; "bar", 43 ] |> Map.ofList;;
val dic : Map = map [("bar", 43); ("foo", 42)]
> printfn "%A" dic;;
map [("bar", 43); ("foo", 42)]
val it : unit = ()
Well, looks a bit strange at first. Let’s ignore the additional output for now. What bothers me is the “|> Map.ofList”. I bet that I will forget to write this most of the time. 🙂
For an overview of working with associative arrays in different programming languages, there is a nice article in Wikipedia.