Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a protocol by delegating to existing functions

Tags:

elixir

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.

like image 432
Hugo Wood Avatar asked Aug 13 '13 21:08

Hugo Wood


1 Answers

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
like image 59
mike Avatar answered Sep 30 '22 03:09

mike