我正在通过建模棋盘游戏来学习Elixir,我有这个代码:
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
实现看起来更复杂。实际上,can_handle_move
只是Enum.empty?
而handle_move
只是List.delete
。 Elixir有办法表达这个吗?类似的东西:
defimpl Board, for: List do
def can_handle_move = &Enum.empty?/1
def handle_move = &List.delete/2
end
...不编译。我也试过没有def
s。
答案 0 :(得分:7)
请尝试Kernel#defdelegate/2
。
defimpl Board, for: List do
defdelegate can_handle_move(self), to: Enum, as: :empty?
defdelegate handle_move(self, move), to: List, as: :delete
end