通过委派现有功能来实现协议

时间:2013-08-13 21:39:33

标签: elixir

我正在通过建模棋盘游戏来学习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。

1 个答案:

答案 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