Skip to content

Instantly share code, notes, and snippets.

@Adzz
Created May 29, 2018 22:31
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 Adzz/b0174a5814fe07a0e65acfe01a5cc693 to your computer and use it in GitHub Desktop.
Save Adzz/b0174a5814fe07a0e65acfe01a5cc693 to your computer and use it in GitHub Desktop.
defmodule Perimeter do
defstruct []
end
defprotocol PerimeterProtocol do
def calculate(shape)
end
defimpl Shape, for: Perimeter do
def calculate(%Perimeter{}, shape) do
PerimeterProtocol.calculate(shape)
end
end
# Now we can implement the PerimeterProtocol for any shape:
defimpl PerimeterProtocol, for: Square do
def calculate(%Square{side: side}) do
side * 4
end
end
defimpl PerimeterProtocol, for: Circle do
def calculate(%Circle{radius: radius}) do
radius * 2 * 3.14
end
end
Shape.calculate(%Perimeter{}, %Square{side: 10})
Shape.calculate(%Perimeter{}, %Circle{radius: 10})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment