[m-users.] Passing field access functions to map?

Zoltan Somogyi zoltan.somogyi at runbox.com
Mon Dec 21 08:31:04 AEDT 2020


2020-12-21 03:57 GMT+11:00 "Jeremy W. Sherman" <jeremyw.sherman at gmail.com>:
> They seem to work fine when applied directly, e.g. f(HasField), and
> with record syntax, e.g. HasField^f, but I can't work out how to pass
> either flavor of field function directly to a function like map or
> fold, whether with or without currying.

Sections 3.4.1 and 3.4.2 of the Mercury reference manual state that
if you want to use getter and setter field access functions as higher order terms,
(i.e. if you want to pass them to functions or predicates such as map and fold),
then you have to either wrap a lambda expression around them, or to write
a declaration for them. Not a definition (the compiler will write that for you),
but a declaration. The attached file is an example.

The reason is that direct uses of field access, such as HasField ^ f or HasField ^ f := X,
are implemented using inline unifications, with no need for any function calls.
Since the vast majority of field names are never used in higher order code,
the compiler does not generate getter or setter functions for fields by default.
Programmers effectively request the compiler to generate those functions
by writing down their declarations, or by writing the lambda expressions.

Having the compiler generate two functions (a getter and a setter) for
every field, without knowing whether they can ever be referred to,
would be wasteful. Generating them on demand, as the need for them
is discovered, would be possible, but it would require a completely
separate code path for them to go through the phases before typechecking,
with the attended requirement for double maintenance. We judged
that the required effort is not worth it, given that the benefit is no more
than the avoidance of a requirement for one line of declaration.
For most people, the time they would need to type the declarations
of all the field access functions they want to use in higher order code
in a year would be less than the time they would need to write an email
about it :-)

Zoltan.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: field_access_example.m
Type: application/octet-stream
Size: 539 bytes
Desc: not available
URL: <http://lists.mercurylang.org/archives/users/attachments/20201221/5ee9e098/attachment.obj>


More information about the users mailing list