Agents in Elixir
A note jar kept by an Agent: state lives in a process, not in a variable.
# An Agent is a small process whose whole job is holding state.
{:ok, jar} = Agent.start_link(fn -> [] end)
Agent.update(jar, fn notes -> ["sharpen the scythe" | notes] end)
Agent.update(jar, fn notes -> ["patch the beehive roof" | notes] end)
IO.puts("notes saved: #{Agent.get(jar, fn notes -> length(notes) end)}")
Agent.get(jar, fn notes -> notes end)
|> Enum.each(fn note -> IO.puts("- " <> note) end)
Agent.stop(jar)
How it works
Agent.start_linkboots the process with an empty list as its state.- Each
Agent.updateprepends a note by running a function on the current state. Agent.getreads through a function too, andAgent.stopretires the jar.
Keywords and builtins used here
AgentEnumIOendfn
The run, in numbers
- Lines
- 12
- Characters to type
- 425
- Tokens
- 116
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 99 seconds.
Step 3 of 3 in Processes, step 24 of 27 in Language basics.