5

I have an implementation of a Balanced Search Tree in elixir which serves as a key value store.

I have a method from_list which takes a list of key value tuples and returns a tree with them. Is there a way to use generics to typespec this the way I would do in a strongly typed language?

@spec from_list([{key_type, value_type}]) :: tree(key_type, value_type)
def from_list(list), do: 

When I try this I get an error. Are there generics in Elixir? Or do I have to just make it a list of type {any, any}?

Colton Voege
  • 409
  • 2
  • 5
  • 12
  • The `MapSet` module defines types that are somewhat like generics (see types of `difference` and `union`): https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/map_set.ex, but Dialyzer doesn't seem to be actually using that extra info while type checking. – Dogbert May 23 '17 at 17:57

1 Answers1

8
@spec from_list([{key_type, value_type}]) :: tree(key_type, value_type) when key_type: var, value_type: var

From Typespecs — Elixir [latest]:

Guards can be used to restrict type variables given as arguments to the function.

@spec function(arg) :: [arg] when arg: atom

If you want to specify more than one variable, you separate them by a comma.

@spec function(arg1, arg2) :: [arg1, arg2] when arg1: atom, arg2: integer

Type variables with no restriction can also be defined using var.

@spec function(arg) :: [arg] when arg: var
Community
  • 1
  • 1
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487