Elixir类型规范和参数化类型变量



我正试图找出如何在Elixir类型和函数规范中组合参数化类型类型变量。举个简单的例子,假设我正在定义一个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函数的类型规范应该是什么来强制执行它。在Erlang中,我非常确信这种语法会起作用:

-spec push(Stack, Value) -> Stack when Stack :: Stack.t(Value).

有没有一种方法可以使用Elixir @spec来表达这种约束?

(我对普通Erlang更流利,但代码应该很容易移植。)

如果你写一个单独的int_push/2(就像你写new_int_stack/0一样),那么你当然可以写:

-spec int_push(integer(), stack(integer())) -> stack(integer()).

这应该允许Dialyzer检测滥用,纯粹是因为Item参数被指定为integer()

最接近通用规范的是:

-spec push(T, stack(T)) -> stack(T) when T :: term().

不幸的是,从Erlang18开始,Dialyzer并没有从最严格的意义上阅读这个规范(要求所有实例T都是可统一的)。它只需要每个T都是一个term()

因此,二郎和长生不老药都不会发出任何警告。

Erlang:中示例的完整代码

-module(stack).
-export([new/0, new_int_stack/0, push/2, test/0]).
-type stack()  :: stack(any()).
-type stack(T) :: list(T).
-spec new() -> stack().
new() ->
  [].
-spec push(T, stack(T)) -> stack(T) when T :: term().
push(Item, Stack) ->
  [Item|Stack].
-spec new_int_stack() -> stack(integer()).
new_int_stack() ->
  new().
-spec test() -> ok.
test() ->
  A = new(),
  B = new_int_stack(),
  push(foo, B),
  ok.

相关内容

最新更新