Skip to content

Instantly share code, notes, and snippets.

@Adzz
Last active February 20, 2018 15:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Adzz/77344ef43a5c1c5c4d818370a6bdff67 to your computer and use it in GitHub Desktop.
Save Adzz/77344ef43a5c1c5c4d818370a6bdff67 to your computer and use it in GitHub Desktop.
defmodule Square do
defstruct [:side]
end
defmodule Circle do
defstruct [:radius]
end
defmodule EquilateralTriangle do
defstruct [:side]
end
defprotocol Shape do
def area(shape)
end
defimpl Shape, for: Square do
def area(shape) do
shape.side * shape.side
end
end
defimpl Shape, for: Circle do
def area(shape) do
shape.radius * shape.radius * 3.14
end
end
defimpl Shape, for: EquilateralTriangle do
def area(shape) do
# some basic high school math that I've forgotten :(
end
end
defmodule Project do
def total_cost(shape, cost_per_square_meter) do
Shape.area(shape) * cost_per_square_meter
end
end
triangle = %EquilateralTriangle{side: 10}
square = %Square{side: 10}
circle = %Circle{radius: 10}
Project.total_cost(triangle, 20)
Project.total_cost(square, 20)
Project.total_cost(circle, 20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment