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.

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, ...

Get Programming Elixir 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.