A different semantics for WeakMap#get default value

Jason Orendorff jason.orendorff at gmail.com
Thu Jan 19 11:25:20 PST 2012


On Thu, Jan 19, 2012 at 12:51 AM, Mark S. Miller <erights at google.com> wrote:
> Hi Jason, I like the idea that the Python defaultdict seems almost to be,
> which I'll call an InfiniteMap. For JS, the following InfiniteMap actually
> obeys the Map contract while implementing a Map with an infinite number of
> key-value mappings. It's initial state is total -- it provides a mapping for
> every key, and so, in this initial state, infMap.has(key) would always
> return true. It does this by using the lazyFactory function as needed to
> make the infinite population of values initially associated with each of the
> infinite population of keys.

That was my first impression too, during the 2006 discussion when
defaultdict was being designed. The issue was raised. But Guido
intentionally made defaultdict inconsistent with the Mapping contract,
on the grounds that being able to access the actual data was much more
important than the invariant. He was right. I think InfiniteMap would
be unsuitable for most defaultdict use cases. Consider:

    # Python
    def mostFrequentWord(words):
        counts = defaultdict(lambda: 0)
        for word in words:
            counts[word] += 1
        return max(counts.keys(), key=lambda w: counts[w])

    // ES with InfiniteMap
    function mostFrequentWord(words) {
        var counts = InfiniteMap(function () { return 0; });
        for (var word of words)
            counts.set(word, counts.get(word) + 1);
        //...now what?
    }

Defaulting is useful when building a data structure. But data
structures also need to be queried, aggregated, and updated, and at
that point the program usually needs to see the data as it is—an
impenetrable illusion of infinity is counterproductive.

Anyway, note that David's motivating use cases are *not* cases where
he needs to pass the Map to Map-consuming library code and needs an
object that satisfies Map's contract. Rather, Map is being used as a
concrete type (as usual for core types) and its API is just clumsy for
this particular purpose. That need can be addressed directly.

-j


More information about the es-discuss mailing list