Cross-language comparison: function map and similar

Terry Reedy tjreedy at udel.edu
Wed Aug 16 14:07:17 EDT 2017


On 8/16/2017 10:53 AM, Steve D'Aprano 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'].

The comprehension 'while' proposal is for future Python 3.  Asking your 
while question the restricted context of Python 2 encouraged the 
restricted list-based or concrete-collection-based thinking about 
comprehensions that you got in some of the answers.  The above snipper 
is only true for Python-2 . In Python 3,

 >>> oracle = map(chr, [65, 66, 67, 68])
 >>> oracle
<map object at 0x000001EC5BD27048>
 >>> next(oracle)
'A'
 >>> next(oracle)
'B'
 >>> next(oracle)
'C'

When oracle is asked for the next value, it asks base_oracle = 
iter(iterable) for a value.  If base_oracle gives one, oracle gives 
func(value).  If base_iterable raises StopIteration, so does oracle. 
This process is inherently sequential.  It remains so with multiple 
input iterables.

 >>> next(oracle)
'D'
 >>> next(oracle)
Traceback (most recent call last):
   File "<pyshell#14>", line 1, in <module>
     next(oracle)
StopIteration

Even in pre-2.2 Python, map's input was not restricted to being a list, 
but could be any 'sequence'.  From 2.0 doc: "The list arguments may be 
*any kind of sequence*" [emphasis added].

I am rather sure that in this context, a 'sequence' was merely something 
that could be indexed and that a pre-defined length was not required. 
This means that map could use the old iterator protocol.  So 'sequence' 
meant 'iterator' in current terms.  The old spelling of 'next(iterator)' 
was 'iterator[i]' where i is 0 for the first request for an object and 
incremented thereafter. The 'sequence' was free to ignore i when 
generating the return object.  It could also use external input.

> 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?

If map's collection input is unbounded, as with Python, a right-to-left 
or completely parallel order is not possible.  If the input oracle 
creates objects on demand, as Python allows, then doing anything other 
that applying func as objects are made available requires internal 
storage.  Asking an oracle for millions of objects when only the first 
few are needed, is foolish.  Storing millions or billions of objects all 
at once when there are only needed one at a time is also foolish.  Which 
is why map and filter were changed in Python 3.

-- 
Terry Jan Reedy




More information about the Python-list mailing list