Skip to content

Instantly share code, notes, and snippets.

@petros

petros/rpg.ex Secret

Last active August 24, 2022 18:37
Show Gist options
  • Save petros/2d1b7a62e01f005244eaf68971126a82 to your computer and use it in GitHub Desktop.
Save petros/2d1b7a62e01f005244eaf68971126a82 to your computer and use it in GitHub Desktop.
Bread And Potions - Elixir - Exercism
defmodule RPG do
defmodule Character do
defstruct health: 100, mana: 0
end
defmodule LoafOfBread do
defstruct []
end
defmodule ManaPotion do
defstruct strength: 10
end
defmodule Poison do
defstruct []
end
defmodule EmptyBottle do
defstruct []
end
defprotocol Edible do
@spec eat(t(), %RPG.Character{}) :: any()
def eat(item, character)
end
defimpl Edible, for: LoafOfBread do
@spec eat(%RPG.LoafOfBread{}, %RPG.Character{}) :: {nil, %RPG.Character{}}
def eat(_item, character), do: {nil, %Character{character | health: character.health + 5}}
end
defimpl Edible, for: ManaPotion do
@spec eat(%RPG.ManaPotion{}, %RPG.Character{}) :: {%RPG.EmptyBottle{}, %RPG.Character{}}
def eat(item, character),
do: {%RPG.EmptyBottle{}, %Character{character | mana: character.mana + item.strength}}
end
defimpl Edible, for: Poison do
@spec eat(%RPG.Poison{}, %RPG.Character{}) :: {%RPG.EmptyBottle{}, %RPG.Character{}}
def eat(_item, character), do: {%RPG.EmptyBottle{}, %Character{character | health: 0}}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment