A Bigger Example
Let’s rewrite our anagram code to use both tasks and an agent.
We’ll load words in parallel from a number of separate dictionaries. A separate task handles each dictionary. We’ll use an agent to store the resulting list of words and signatures.
| defmodule Dictionary do |
| |
| @name __MODULE__ |
| |
| ## |
| # External API |
| |
| def start_link, |
| do: Agent.start_link(fn -> %{} end, name: @name) |
| |
| def add_words(words), |
| do: Agent.update(@name, &do_add_words(&1, words)) |
| |
| def anagrams_of(word), |
| do: Agent.get(@name, &Map.get(&1, signature_of(word))) |
| |
| ## |
| # Internal implementation |
| |
| defp do_add_words(map, words), |
| do: Enum.reduce(words, map, &add_one_word(&1, &2)) |
| |
| defp ... |
Get Programming Elixir 1.3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.