April 2016
Beginner to intermediate
300 pages
6h 58m
English
Functional programs are stateless, but we still need to be able to manage state. In Elixir, we use concurrent processes and recursion to handle this task. That may sound counterintuitive, but let’s take a look at how it works with a simple program.
Let’s create a Counter server that counts up or down. Create a lib/rumbl/counter.ex file and key this in:
| 1: | defmodule Rumbl.Counter do |
| - | |
| - | def inc(pid), do: send(pid, :inc) |
| - | |
| 5: | def dec(pid), do: send(pid, :dec) |
| - | |
| - | def val(pid, timeout \\ 5000) do |
| - | ref = make_ref() |
| - | send(pid, {:val, self(), ref}) |
| 10: | receive do |
| - | {^ref, val} -> val |
| - | after timeout -> exit(:timeout) |
| - | end |
| - | end ... |