I am trying to figure out how to combine parameterized types and type variables in Elixir type and function specs. As a simple example, let's say I am defining a Stack
module:
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
Using the parameterized type spec on line 3, I can define a function that creates a new stack that should contain only integers:
@spec new_int_stack() :: Stack.t(integer)
def new_int_stack(), do: Stack.new
So far, so good. Now I want to make sure that only integers can be pushed into this stack. For example, dialyzer should be fine with this:
int_stack = new_int_stack()
Stack.push(int_stack, 42)
But dialyzer should complain about this:
int_stack = new_int_stack()
Stack.push(int_stack, :boom)
I can't figure out what the type spec on the push
function should be to enforce that. In Erlang, I'm pretty sure this syntax would do the trick:
-spec push(Stack, Value) -> Stack when Stack :: Stack.t(Value).
Is there a way to express this constraint using Elixir @spec
?