Skip to content

Instantly share code, notes, and snippets.

@jackmarchant
Last active October 12, 2018 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmarchant/c97b1cd6c4d22b089e6352279184d4e2 to your computer and use it in GitHub Desktop.
Save jackmarchant/c97b1cd6c4d22b089e6352279184d4e2 to your computer and use it in GitHub Desktop.
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
@chgeuer
Copy link

chgeuer commented Oct 12, 2018

:math.pow(circle.radius, 2) * :math.pi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment