[m-users.] Why can't there be multiple field constructor field names in the same module?

Zoltan Somogyi zoltan.somogyi at runbox.com
Thu Oct 14 12:34:02 AEDT 2021


2021-10-14 11:55 GMT+11:00 "Philip White" <philip at pswhite.org>:
> I'm getting an error like "field abc multiply defined" for type
> definitions like the following:
> 
> :- type x ---> x(abc :: int).
> :- type y ---> y(abc :: int).
> 
> The error is quite clear, so I'm not confused what it's complaining
> about; I'm just confused *why*. Is there a fundamental reason that
> having fields with the same name in the same module is unacceptable, or
> has no one yet implemented support for it?

There is a reason, though whether that reason is "fundamental" or not
is a matter of opinion. 

As part of its implementation of field names, the compiler implicitly defines
two functions for each field: the field's getter function, and its setter function.
The names of these are derived from the field name. (The getter function's name
is the field name itself, the setter's name is the field name followed by " :=".)
This design choice is baked into the compiler. It allows the compiler's
internal representation of the program to be compiled to treat both
read and write accesses to fields as simple function calls, with a relatively
small fraction of the compiler having to care about field access functions
being different from other functions. It also allows programmers to override
both getters and setters if needed, simply by defining functions
with the right name.

It is this fact that requires the limitation you are complaining about.
The code above would generate two functions named abc,
whose declarations would be

:- func abc(x) = int.
:- func abc(y) = int.

The compiler does not allow this: it requires that a function's
(or a predicate's) name and arity determine its argument types
without ambiguity. This requirement extends to all function
(and predicate) declarations, whether they are written by the user,
or generated by the compiler. (The same issue of course also arises
for the field setter functions.)

The compiler could of course be modified to allow ambiguity
in function name/arity pairs, field names, or both. It would require
a large amount of work. And then there is the fact that in the presence of
ambiguities such as whether abc is a field of x or y, error messages
about e.g. type errors involving abc would have to be more complex
and therefore harder to read. Also, the code generating those error
messages would have be prepared for the presence of ambiguities
even when they are not actually present.

Given that the workaround is so trivial, and that the benefit comes
with nontrivial downsides, the effort to benefit ratio of the change
you are asking for is quite high.

Zoltan.


More information about the users mailing list