Skip to content

Instantly share code, notes, and snippets.

@brainlid
Created Feb 27, 2020
Embed
What would you like to do?
Row Polymorphism example in Elixir
defmodule Point2D do
defstruct [x: 0, y: 0]
end
defmodule Point3D do
defstruct [x: 0, y: 0, z: 0]
end
defmodule RowPolymorphism do
def get_x_y(%{x: x, y: y} = _data) do
{x, y}
end
end
p1 = %Point2D{x: 10, y: 3}
p2 = %Point3D{x: 1, y: 5, z: 11}
RowPolymorphism.get_x_y(p1)
#=> {10, 3}
RowPolymorphism.get_x_y(p2)
#=> {1, 5}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment