3
我试图找出如何结合参数化类型和类型变量在药剂类型和功能规格。举一个简单的例子,假设我定义一个Stack
模块:药剂型规格和参数化类型变量
defmodule Stack do
@type t :: t(any)
@type t(value) :: list(value)
@spec new() :: Stack.t
def new() do
[]
end
# What should the spec be?
def push(stack, item) do
[item|stack]
end
end
第3行使用参数化类型规范,我可以定义,创建一个新的堆栈应该只包含整数的函数:
@spec new_int_stack() :: Stack.t(integer)
def new_int_stack(), do: Stack.new
到目前为止,这么好。现在我想确保只有整数可以被推入这个堆栈。例如,透析器应罚款与此:
int_stack = new_int_stack()
Stack.push(int_stack, 42)
但透析器应该抱怨这一点:
int_stack = new_int_stack()
Stack.push(int_stack, :boom)
我想不通的push
功能的型号规格应执行什么。在二郎,我敢肯定,这句法会做的伎俩:
-spec push(Stack, Value) -> Stack when Stack :: Stack.t(Value).
有表达使用药剂@spec
此约束的方法吗?