May 2018
Intermediate to advanced
412 pages
9h 3m
English
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 add_one_word(word, ... |
Read now
Unlock full access