Last active
October 12, 2018 05:46
-
-
Save jackmarchant/c97b1cd6c4d22b089e6352279184d4e2 to your computer and use it in GitHub Desktop.
This file contains 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
defprotocol Area do | |
@doc "Calculate the area for a given object" | |
def area(object) | |
end | |
defimpl Area, for: Rectangle do | |
def area(rectangle) do | |
rectangle.width * rectangle.length | |
end | |
end | |
defimpl Area, for: Circle do | |
def area(circle) do | |
:math.pow(circle.radius * :math.pi, 2) | |
end | |
end | |
# These are arbritrary shape structs, but ignoring that fact, | |
# we have defined a protocol and a couple of implementations. | |
# Usage is then as easy as: | |
iex> Area.area(%Rectangle{width: 5, length: 3}) | |
15 | |
iex> Area.area(%Circle{radius: 5}) | |
246.74011002723395 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:math.pow(circle.radius, 2) * :math.pi