たまたま見つけて。
- Comparing protocols and extensions in Swift and Elixir
ElixirはClojureに影響されているのですね。protocol周辺の使い道。
パッと、 defimpl の対象となるタイプを思い出せなかったので以下にURLを一応。
http://elixir-lang.org/docs/stable/elixir/Kernel.html#defprotocol/2
こんな感じ。 defimpl の 第一引数のタイプ によって、どのタイプに対する実装かを示しています。
defprotocol JSONA do
def to_json(data, precision)
end
defprotocol JSONB do
def to_json(data, scale)
end
defimpl JSONA, for: BitString do
def to_json(data, _precision) do
"hello"
end
end
defimpl JSONA, for: Integer do
def to_json(data, _precision) do
Integer.to_string(data)
end
end
JSONA.to_json "abc", 10
|> IO.puts
Swiftは、記事のものは古いので省略。も少しあとで。