10
votes

In statically typed languages with generics, like C#, I can specify in the method signature that each of the map's keys is an atom and each value is a list of {string, int} tuple. How do I define the type specification for function arguments like that in Elixir?

PS: if you are reading this and have >1500 rating, could you please create a type-specification tag.

2
I'm not familiar with elixir, but it claims to be a "dynamic language", which usually means that it does not have a formal type system. So... use a comment?luqui
it has type specifications, which can be used by the static analysis tool Dialyzer - elixir-lang.org/docs/stable/Kernel.Typespec.htmltldr

2 Answers

15
votes

You would define it like so:

@type bar :: %{atom => [{binary, integer}]}

@spec foo(bar) :: bar
def foo(bar), do: bar

The above defines a new type, which is your map of atom keys to lists of binary/integer tuples, and then uses that type in the type spec for foo.

1
votes

For inline spec it goes like this:

defmodule LousyCalculator do
  @spec add(number, number) :: {number, String.t}
  def add(x, y), do: {x + y, "You need a calculator to do that?!"}

  @spec multiply(number, number) :: {number, String.t}
  def multiply(x, y), do: {x * y, "Jeez, come on!"}
end

If you expect a structure then the type is:

@spec struct_returner_and_getter(%Struct_name1{}) :: %Struct_name2{}

Source: http://elixir-lang.org/getting-started/typespecs-and-behaviours.html