Skip to content

Instantly share code, notes, and snippets.

@lagenorhynque
Last active May 25, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagenorhynque/6eb6452d26b4cc57c470c3b37371463d to your computer and use it in GitHub Desktop.
Save lagenorhynque/6eb6452d26b4cc57c470c3b37371463d to your computer and use it in GitHub Desktop.
Simple counter programs in Elixir & Clojure
user> (defn counter [init]
(let [c (atom init)]
#(swap! c + %)))
#'user/counter
user> (def c1 (counter 0))
#'user/c1
user> (def c2 (counter 0))
#'user/c2
user> (c1 2)
2
user> (c2 3)
3
user> (c1 2)
4
user> (c2 3)
6
iex(1)> defmodule Counter do
...(1)> def loop(init) do
...(1)> receive do
...(1)> {pid, x} ->
...(1)> next = init + x
...(1)> send(pid, next)
...(1)> loop(next)
...(1)> end
...(1)> end
...(1)> end
{:module, Counter,
<<70, 79, 82, 49, 0, 0, 5, 8, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 133, 0,
0, 0, 15, 14, 69, 108, 105, 120, 105, 114, 46, 67, 111, 117, 110, 116, 101,
114, 8, 95, 95, 105, 110, 102, 111, 95, ...>>, {:loop, 1}}
iex(2)> c1 = spawn(Counter, :loop, [0])
#PID<0.119.0>
iex(3)> c2 = spawn(Counter, :loop, [0])
#PID<0.121.0>
iex(4)> send(c1, {self, 2})
{#PID<0.104.0>, 2}
iex(5)> send(c2, {self, 3})
{#PID<0.104.0>, 3}
iex(6)> send(c1, {self, 2})
{#PID<0.104.0>, 2}
iex(7)> send(c2, {self, 3})
{#PID<0.104.0>, 3}
iex(8)> flush
2
3
4
6
:ok
iex(1)> defmodule Counter do
...(1)> def new(init) do
...(1)> spawn(__MODULE__, :loop, [init])
...(1)> end
...(1)>
...(1)> def count(counter, x) do
...(1)> ref = make_ref()
...(1)> send(counter, {:count, self(), ref, x})
...(1)> receive do
...(1)> {:ok, ^ref, count} -> count
...(1)> end
...(1)> end
...(1)>
...(1)> def loop(init) do
...(1)> receive do
...(1)> {:count, sender, ref, x} ->
...(1)> count = init + x
...(1)> send(sender, {:ok, ref, count})
...(1)> loop(count)
...(1)> end
...(1)> end
...(1)> end
{:module, Counter,
<<70, 79, 82, 49, 0, 0, 6, 232, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 166,
0, 0, 0, 21, 14, 69, 108, 105, 120, 105, 114, 46, 67, 111, 117, 110, 116,
101, 114, 8, 95, 95, 105, 110, 102, 111, 95, ...>>, {:loop, 1}}
iex(2)> c1 = Counter.new(0)
#PID<0.131.0>
iex(3)> c2 = Counter.new(0)
#PID<0.133.0>
iex(4)> Counter.count(c1, 2)
2
iex(5)> Counter.count(c2, 3)
3
iex(6)> Counter.count(c1, 2)
4
iex(7)> Counter.count(c2, 3)
6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment