Skip to content

Instantly share code, notes, and snippets.

View bmitch's full-sized avatar

Bill Mitchell bmitch

  • Vancouver Island, BC, Canada
View GitHub Profile
@bmitch
bmitch / ticker.ex
Created June 28, 2017 23:21
ticker.ex
defmodule Ticker do
@interval 2000
@name :ticket
def start do
pid = spawn(__MODULE__, :generator, [[]])
:global.register_name(@name, pid)
end
@bmitch
bmitch / pmap.exs
Created June 25, 2017 14:56
Parallel map
defmodule Parallel do
def pmap(collection, fun) do
me = self
collection
|> Enum.map(fn (elem) ->
spawn_link fn -> (send me, { self, fun.(elem) }) end
end)
|> Enum.map(fn (pid) ->
receive do { ^pid, result } -> result end
end)
@bmitch
bmitch / simple_msg.exs
Created June 25, 2017 14:41
simple_msg.exs
defmodule Spawn1 do
def greet do
receive do
{sender, msg} ->
send sender, { :ok, "Hello, #{msg}" }
greet
end
end
end
@bmitch
bmitch / chian.exs
Created June 25, 2017 14:35
chain.exs
defmodule Chain do
def counter(next_pid) do
receive do
n ->
send next_pid, n + 1
end
end
def create_processes(n) do
last = Enum.reduce 1..n, self,
@bmitch
bmitch / organizing-a-project.md
Created June 24, 2017 15:13
organizing-a-project.md

Creating a project tree:

mix new <project name>

Running tests:

mix test
@bmitch
bmitch / elixir-basics.md
Last active June 17, 2017 19:05
elixir-basics.md

Back

Basics

Value Types

Represent numbers, names, ranges and regular expressions.

Integers

Can be written as:

  • decimal (1234).
@bmitch
bmitch / elixir-immutability.md
Last active June 17, 2017 18:38
elixir-immutability.md

Back

Immutability

  • Once a variable a list such as [1, 2 ,3] you know it will always reference those same variables (until you rebind the variable).
  • What if you need to add 100 to each element in [1, 2, 3]? Elixir produces a copy of the original, containing the new values.

This uses the [ head | tail ] operator to build a new list with head as the first element and tail as the rest:

list1 = [3, 2, 1]
@bmitch
bmitch / elixir.md
Last active August 31, 2019 05:14
elixir.md
@bmitch
bmitch / elixir-pattern-matching.md
Last active February 13, 2023 11:24
elixir-pattern-matching.md

Back

Pattern Matching

  • = is not assignment in Elixir. More like an assertion.
  • Succeeds if it can find a way of making left side equal to right side.
a = 1 #1
a + 3 #1

In thise cases the lef side is a variable and right side is an integer literal. So to make the match it binds the variable to the integer.