如何在Elixir中为泛型类型指定类型规范

5

我在Elixir中实现了一棵平衡搜索树,它可以作为键值存储。我有一个名为from_list的方法,它接受一个键值元组列表,并返回一个包含这些键值对的树。是否有一种方法可以使用泛型来对其进行类型规范,就像在强类型语言中所做的那样?

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

当我尝试这样做时,出现了错误。Elixir中是否有泛型?还是我只需要将其作为类型为{any, any}的列表?

MapSet 模块定义了一些类似于泛型的类型(请参见 differenceunion 的类型):https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/map_set.ex,但 Dialyzer 在类型检查时似乎并没有实际使用这些额外信息。 - Dogbert
1个回答

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

来自类型规范 — Elixir [最新版]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接