O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required