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 def
s.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With