[英]How to typespec generics in Elixir
I have an implementation of a Balanced Search Tree in elixir which serves as a key value store. 我在elixir中有一个Balanced Search Tree的实现,它用作键值存储。
I have a method from_list
which takes a list of key value tuples and returns a tree with them. 我有一个方法
from_list
,它使用键值元组的列表并与它们一起返回一棵树。 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?
Elixir中有仿制药吗? Or do I have to just make it a list of type {any, any}?
还是我只需要使其成为{any,any}类型的列表?
@spec from_list([{key_type, value_type}]) :: tree(key_type, value_type) when key_type: var, value_type: var
From Typespecs — Elixir [latest] : 来自Typespecs — 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
.无限制的类型变量也可以使用
var
定义。@spec function(arg) :: [arg] when arg: var
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.