October 2014
Intermediate to advanced
280 pages
7h 20m
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.
| tasks/anagrams.exs | |
| | defmodule Dictionary do |
| | |
| | @name __MODULE__ |
| | |
| | ## |
| | # External API |
| | |
| | def start_link, |
| | do: Agent.start_link(fn -> HashDict.new end, name: @name) |
| | |
| | def add_words(words), |
| | do: Agent.update(@name, &do_add_words(&1, words)) |
| | |
| | def anagrams_of(word), |
| | do: Agent.get(@name, &Dict.get(&1, signature_of(word))) |
| | |
| | ## |
| | # Internal implementation |
| | |
| | defp do_add_words(dict, words), |
| | do: Enum.reduce(words, dict, &add_one_word(&1, ... |
Read now
Unlock full access