Indexing access for Lists and Maps considered harmful?

Neal Gafter neal at gafter.com
Wed Jun 24 08:12:08 PDT 2009


On Wed, Jun 24, 2009 at 7:45 AM, Reinier Zwitserloot <
reinier at zwitserloot.com> wrote:

> I am beginning to see some concensus on this list that the neal
> semantics are the most preferred semantics. That is:
>
> FOO = (a[b] = c);
>
> should be equal to:
>
> a[b] = c;
> FOO = a[b];
>
> and thus, both a setter and a getter call.


I wasn't suggesting that a get operation is required.  I was suggesting that
the specification for the indexing operator must allow the API to provide
the result value of the assignment.  Calling the getter is one (as you've
discovered, poor) way to accomplish that.


> So, to put it in layman's terms: Consistency is an unattainable pipe
> dream - akin to appreciation for a painting, not a quantifiable
> measure.


I think you've demonstrated that you don't know how to achieve it.  That's
not the same as being unattainable.  Here's another way that doesn't require
extension methods:

define a[i] (where a is not an array type) in an rvalue context by
translation as

operator_index_get(a, i)

and a[i] = value by translation as

operator_index_put(a, i, value)

Modulo details about compound operators, some more precision, and API design
advice, that's the gist of the specification.  If you want to use the index
operators with collections, you'd typically import these methods from a
utility class:

import static java.util.Collections.operator_index_get;
import static java.util.Collections.operator_index_put;

and the implementation in Collections would behave as required:

public static <E> E operator_index_put(List<E> list, int index, E value) {
    list.set(index, value);
    return value;
}
public static <K,V> V operator_index_put(Map<K,V> map, K key, V value) {
    map.put(key, value);
    return value;
}

Short, sweet, and satisfies all the requirements.  Not my favorite solution
for this problem space, but better than most of the others that have been
proposed.



More information about the coin-dev mailing list