Skip to content

Instantly share code, notes, and snippets.

@Adzz
Last active May 27, 2018 10:22
Show Gist options
  • Save Adzz/fae540d562a25abf280096a24511cdc2 to your computer and use it in GitHub Desktop.
Save Adzz/fae540d562a25abf280096a24511cdc2 to your computer and use it in GitHub Desktop.
# 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