O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dictionaries

Maps and hashdicts both implement the Dict behaviour. The Keyword module largely does, too, but with some differences to allow for the fact that it supports duplicate keys.

In general, you’ll want to use the Dict module’s methods to access this functionality, as this allows you the flexibility to change the underlying implementation between, say, a map and a hashdict. (This example uses Enum.into, which is how you can easily map one kind of collection into another. We’ll look at this in The Collectable Protocol.)

maps/use_dict.exs
 
defmodule​ Sum ​do
 
def​ values(dict) ​do
 
dict |> Dict.values |> Enum.sum
 
end
 
end
 
 
# Sum a HashDict
 
hd = [ one: 1, two: 2, three: 3 ] |> Enum.into HashDict.new
 
IO.puts Sum.values(hd) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required