October 2014
Intermediate to advanced
280 pages
7h 20m
English
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) ... |
Read now
Unlock full access