[erlang-questions] spec declaration for single list parameter with fixed size

Kostis Sagonas kostis@REDACTED
Mon Jul 4 15:37:56 CEST 2011


Jesper Louis Andersen wrote:
> On Sun, Jul 3, 2011 at 11:58, Michael Richter <ttmrichter@REDACTED> wrote:
>> On 3 July 2011 16:10, Roberto Ostinelli <roberto@REDACTED> wrote:
>>> a very stupid spec declaration question. how can you declare the specs of
>>> a function which has a single list with multiple arguments?
>>>
>>> For instance, consider this function:
>>
>>> myfun([One, Two]) ->
> 
> This is better since you then have a product type rather than a
> recursive type on lists. It is much simpler to work with from a typing
> perspective. Also note that you would not easily be able to type
> ["hello", 5] in a statically typed language without resorting to
> either some kind of type tagging, polymorphic variants or existential
> types.
> 
> My advice would be to alter the structure of the function such that it
> is easier to type. It tends to be safer from a programming perspective
> as well.

Both Jesper and Michael have given very good advice on this topic, but 
for the record, I guess, let me add my two cents here.

First of all, as others have mentioned, when grouping together a fixed 
number of items, tuples rather than lists should better be used. Not 
only does this make sense from a typing perspective, but for more than 
one item tuples are also more memory efficient and thus slightly faster. 
For example [One, Two] needs 4 words while {One, Two} needs 3.

Coming back to the original question, it's pretty clear that what the 
type language does it to make a abstraction over all terms (which belong 
to some type) and thus cannot possibly express all programmer intentions 
accurately. For example, it is currently not possible to declare lists 
with a certain number of elements, partly due to the fact that the type 
language has decided to make [T] an alias for list(T). Even if this 
constraint was lifted (e.g. [T] stood for a one element list for items 
of type T, [T1,T2] for a two element list of items of type T1 and T2, 
etc.) the type language would not be able to express all programmer 
intentions (e.g. lists of an even number of elements, lists whose length 
is a prime number, lists where the middle element is 42, etc.). This is 
fundamental limitation of all type languages: no matter how expressive 
they become, there are things that cannot (conveniently) be expressed in 
them.

Kostis



More information about the erlang-questions mailing list