Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View Adzz's full-sized avatar

Adam Lancaster Adzz

View GitHub Profile
defprotocol Zip do
def apply(collection_1, collection_2, operation)
end
# We can implement it for lists:
defimpl Zip, for: List do
def apply(a, b, calculate) do
Enum.zip(a, b)
|> Enum.map(fn {a, b} -> calculate.(a, b) end)
end
list_1 = [1, 2]
list_2 = [3, 4]
Zip.apply(list_1, list_2, fn x, y -> x + y end) #=> [4, 6]
defmodule Test do
def thing() do
1+1
end
defmacro my_macro do
quote do
1 + 1
end
end
@Adzz
Adzz / ecto_morph.ex
Last active April 14, 2019 19:52
Ecto Morph blog post
response = %{"meat_type" => "medium rare", "pickles" => false, "collection_date" => "2019-11-04"}
# We want a struct so that we can do things like implement protocols for it
defmodule SteamedHam do
defstruct [:meat_type, :pickles, :collection_date]
end
# With no !, the struct function selects only the fields defined in the schema.
steamed_ham = struct(SteamedHam, response)
@Adzz
Adzz / triple.ex
Last active November 28, 2018 16:05
defmodule AmazeOn do
defstruct [price: 10]
end
defmodule Area do
defstruct []
end
defmodule Square do
defstruct [:side]
defmodule Perimeter do
defstruct []
end
defprotocol PerimeterProtocol do
def calculate(shape)
end
defimpl Shape, for: Perimeter do
def calculate(%Perimeter{}, shape) do
defmodule Circle do
defstruct [:radius]
end
defimpl AreaProtocol, for: Circle do
def calculate(%Circle{radius: radius}) do
3.14 * radius * radius
end
end
defmodule Square do
defstruct [:side]
end
defmodule Area do
defstruct []
end
defprotocol Shape do
def calculate(calculation, shape)
Shape.calculate(:area, %Square{side: 10})
defmodule Square do
defstruct [:side]
end
defmodule Circle do
defstruct [:radius]
end
defprotocol Area do