Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elixir: defining type specification for maps/hashdicts

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.

like image 754
tldr Avatar asked May 13 '14 02:05

tldr


2 Answers

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.

like image 190
bitwalker Avatar answered Oct 16 '22 12:10

bitwalker


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

like image 26
Maja Savić Avatar answered Oct 16 '22 10:10

Maja Savić