5

我正在通过对棋盘游戏建模来学习 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_moveis justEnum.empty?handle_moveis just List.delete。Elixir 有办法表达这一点吗?就像是:

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

...无法编译。我也试过没有defs。

4

1 回答 1

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
于 2013-08-14T04:44:43.957 回答