Cross-language comparison: function map and similar

Chris Angelico rosuav at gmail.com
Thu Aug 17 04:06:24 EDT 2017


On Thu, Aug 17, 2017 at 3:54 PM, Pavol Lisy <pavol.lisy at gmail.com> wrote:
> On 8/16/17, Steve D'Aprano <steve+python at pearwood.info> wrote:
>> Over in another thread, we've been talking about comprehensions and their
>> similarities and differences from the functional map() operation.
>>
>> Reminder:
>>
>> map(chr, [65, 66, 67, 68])
>>
>> will return ['A', 'B', 'C'].
>>
>> My questions for those who know languages apart from Python:
>>
>> Are there language implementations which evaluate the result of map() (or
>> its
>> equivalent) in some order other than the obvious left-to-right first-to-last
>> sequential order? Is that order guaranteed by the language, or is it an
>> implementation detail?
>
> Is it guaranteed in python? Or future version could implement map with
> something like subscriptability "propagation"?
>
>>>>range(1_000_000_000_000_000_000)[-1]
> 9999999999999999
>
>>>> map(lambda a:a+1,range(1_000_000_000_000_000_000))[-1]
> TypeError: 'map' object is not subscriptable

I think it is, partly because of the behaviour of map with additional
arguments. If you want something subscriptable, you probably don't
want an iterable, but a mapping type (it's no coincidence that the
words are similar). The Python map() function expects a function and
one or more iterables, and returns an iterator; but if you instead
give it a function and a (subscriptable) collections, you could have
it be a collection. (I'm not sure what to do about multiple
collections. I guess you'd do something similar to map() - if any
subcollection raises, Map raises. Not implemented here though.)

class Map(dict):
    def __init__(self, func, coll):
        self.func, self.coll = func, coll
    def __missing__(self, key):
        self[key] = self.func(self.coll[key])
        return self[key]

This has the same subscripting semantics as the underlying collection,
and will cache any result it sees. But watch out! It can't know about
subscript aliasing, and will treat a key of -1 as completely different
from any positive subscript. It also doesn't iterate the same way as
the underlying collection does:

>>> spam = Map(print, range(10))
>>> list(spam)
[]

Without knowing exactly what kind of "thing" you're mapping over, it's
impossible to get everything right.

ChrisA



More information about the Python-list mailing list