通过委派现有功能来实现协议 [英] Implementing a protocol by delegating to existing functions
本文介绍了通过委派现有功能来实现协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过模拟棋盘游戏来学习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
实现看起来确实更复杂。实际上, can_handle_move
只是 Enum.empty?
和 handle_move
只是 List.delete
。 Elixir有办法表达这一点吗?例如:
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
...不会编译。我也尝试过不使用 def
s。
...which doesn't compile. I've also tried without the def
s.
推荐答案
尝试 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
这篇关于通过委派现有功能来实现协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文