Currently we have in the stdlib Protocol.assert_impl!/2 that raises an exception if the given module does not implement the protocol.
I think would be nice if we had a function with a similar behavior, used to check if the module implements a protocol, but return true or false.
The use case that I have in mind, to use this function, is when serializing values that may be structs would be useful to just add a simple if/else to check if it implements a behavior like String.Chars or Enumerable.
To implement this kind of functionality today I would need to try/rescue.
# enumerable
def serialize(data) when is_map(data) do
data
|> Enum.map(fn {key, value} -> {serialize_key(key), serialize(value)} end)
|> Enum.into(%{})
rescue
Protocol.UndefinedError -> serialize_struct(value)
end
# String.Chars
def serialize_string(%mod{} = value)
try do
Protocol.assert_impl!(String.Chars, mod)
to_string(value)
rescue
Protocol.UndefinedError -> serialize_struct(value)
end
end
Does it makes sense? Am I missing something? A predicate function to check if a protocol is implemented would be something acceptable in the stdlib?