Last active
February 20, 2018 15:10
-
-
Save Adzz/77344ef43a5c1c5c4d818370a6bdff67 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 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