[erlang-questions] Trouble with init/1 spec

Kostis Sagonas <>
Wed Mar 24 17:00:52 CET 2010


Jay Nelson wrote:
> I am having trouble specifying an init/1 function.  This should be a 
> problem for most gen_xxx applications that use records for State, so I 
> must have not used the right query terms to search the archives.
> 
> Here is my init/1 function for a gen_fsm:
> 
> -spec init(list()) -> {ok, ?RECONNECT, #twfsm_state{}}.
>        
> init([Server, Port, User, Pwd]) ->
>     {ok, ?RECONNECT,
>      #twfsm_state{server=Server, port=Port, user=User, pwd=Pwd}}.
> 
> 
> The problem is that I cannot figure out how to specify that I really am 
> passing in a list of the type [string(), non_neg_integer(), string(), 
> string()].

You cannot do that.  The type language is not expressive enough to allow 
the declaration of a 4-element list and this is what's the problem here. 
  However, you can specify a slightly more accurate type than list() 
though (btw, this is also written as [_].)  The type

	[string() | non_neg_integer()]

constrains the input argument better than list()

>  Declaring it as list(any()) means the fields on the record 
> have to all be declared any().  As long as my port field is declared 
> non_neg_integer() in the record definition, I can't get past the 
> dialyzer warning.

Huh?  Are you sure?  The record fields can be declared whatever type you 
want.  I am not sure to what dialyzer warning you are referring to, but 
perhaps we can take this off list.

> On a separate note non_neg_integer() is equivalent to 0..
> Can the user declare something like my_lucky_numbers() = 12..17 or is 
> the integer .. notation just used to explain what happens internally for 
> the special built-in types?

Well, sort of. The .. notation can be used to define your lucky numbers, 
but it can only be used if you specify both a lower and an upper limit.
In other words, this is allowed:

-type my_lucky_number() :: 12..17.

but this one is not:

-type my_lucky_number() :: 12.. .

Kostis


More information about the erlang-questions mailing list