Question

I'm learning Elixir by modeling a board game, and I have this code:

defprotocol Board do
  def can_handle_move(self)
  def handle_move(self, move)
end

defimpl Board, for: List do
  def can_handle_move(self), do: Enum.empty?(self)
  def handle_move(self, move), do: List.delete(self, move)
end

The implementation looks more complicated that it really is. Actually, can_handle_move is just Enum.empty? and handle_move is just List.delete. Does Elixir have a way of expressing this? Something like:

defimpl Board, for: List do
  def can_handle_move = &Enum.empty?/1
  def handle_move = &List.delete/2
end

...which doesn't compile. I've also tried without the defs.

Was it helpful?

Solution

Try Kernel#defdelegate/2 for it.

defimpl Board, for: List do
  defdelegate can_handle_move(self), to: Enum, as: :empty?
  defdelegate handle_move(self, move), to: List, as: :delete
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top