Today I was reading through http://learnyousomeerlang.com/dialyzer and stumbled across this:
-spec convert(tuple()) -> list();
(list()) -> tuple().
convert(Tup) when is_tuple(Tup) -> tuple_to_list(Tup);
convert(L = [_|_]) -> list_to_tuple(L).
Rather than putting
tuple()andlist()types together into a single union, this syntax allows you to declare type signatures with alternative clauses. If you callconvert/1with a tuple, we expect a list, and the opposite in the other case.
I’ve never seen this in Elixir typespecs before and the docs make no mention of Elixir supporting multiple clauses in a type spec. Is this something Elixir supports (or could it in the future)? I can imagine a syntax like:
@spec convert(tuple) :: list @spec convert(list) :: tuple def convert(tup) when is_tuple(tup), do: Tuple.to_list(tup)def convert([_ | _] = list), do: List.to_tuple(list)
Basically, just allowing us to list multiple type spec clauses sequentially like we do with function clauses, with line breaks in between.
If this is already supported, I can work on updating the type spec docs to mention it.
Thanks,
Myron