Skip to content

Latest commit

 

History

History
88 lines (66 loc) · 1.48 KB

File metadata and controls

88 lines (66 loc) · 1.48 KB

Elixir Koans - 19 Protocols

import ExUnit.Assertions

Intro

Want to follow the rules? Adhere to the protocol!

defprotocol(Artist, do: def(perform(artist)))

defimpl Artist, for: Any do
  def perform(_) do
    "Artist showed performance"
  end
end

defmodule Painter do
  @moduledoc false
  @derive Artist
  defstruct name: ""
end

defmodule Musician do
  @moduledoc false
  defstruct(name: "", instrument: "")
end

defmodule Dancer do
  @moduledoc false
  defstruct(name: "", dance_style: "")
end

defmodule Physicist do
  @moduledoc false
  defstruct(name: "")
end

defimpl Artist, for: Musician do
  def perform(musician) do
    "#{musician.name} played #{musician.instrument}"
  end
end

defimpl Artist, for: Dancer do
  def perform(dancer), do: "#{dancer.name} performed #{dancer.dance_style}"
end

Sharing an interface is the secret at school

musician = %Musician{name: "Andre", instrument: "violin"}
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
assert Artist.perform(musician) == ___
assert Artist.perform(dancer) == ___

Sometimes we all use the same

painter = %Painter{name: "Emily"}
assert Artist.perform(painter) == ___

If you are not an artist, you can't show performance

assert_raise ___, fn ->
  Artist.perform(%Physicist{name: "Delia"})
end

Next Steps