Skip to content

Instantly share code, notes, and snippets.

@brainlid
Created February 27, 2020 23:25
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 brainlid/cbe702c18dc955a2bb55077ba99e9fc0 to your computer and use it in GitHub Desktop.
Save brainlid/cbe702c18dc955a2bb55077ba99e9fc0 to your computer and use it in GitHub Desktop.
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