Created
May 29, 2018 22:31
-
-
Save Adzz/b0174a5814fe07a0e65acfe01a5cc693 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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