Last active
May 27, 2018 10:22
-
-
Save Adzz/fae540d562a25abf280096a24511cdc2 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
# Make some shapes | |
defmodule Square do | |
defstruct [:side] | |
end | |
defmodule Circle do | |
defstruct [:radius] | |
end | |
# define the protocol | |
defprotocol Shape do | |
def area(shape) | |
end | |
# implement it for the Square | |
defimpl Shape, for: Square do | |
def area(shape) do | |
shape.side * shape.side | |
end | |
end | |
# implement it for the Circle | |
defimpl Shape, for: Circle do | |
def area(shape) do | |
shape.radius * shape.radius * 3.14 | |
end | |
end | |
Shape.area(%Square{side: 10}) #=> 100 | |
Shape.area(%Circle{radius: 10} #=> 314.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment