python hack of the day -- "listable" functions

Stefan Franke spamfranke at bigfoot.de
Thu May 13 15:50:35 EDT 1999


On 12 May 1999 16:30:34 -0700, Michael Vanier <mvanier at bbb.caltech.edu> wrote:

>
>Having nothing better to do one day, I whipped up a quick class that
>transforms functions into "listable" functions i.e. functions that
>automatically map themselves over a sequence.  The idea was stolen from
>Mathematica, but it's amazing how easy it is to implement this in python.

Or, IOW, 

def listable(f):
    return xapply (map, f)

... if Michael Hudson's recently posted bytecodehacks were only able to hack
those intractable builtins <wink>.

(Some philosophical thoughts follow)
Stefan


PS: Seriously, I have a strong feeling that concept of 'mapping' is much easier
to grok than its 'operational' manifestation as a function. Take for example

x = [1, 2, 3, 4]
y = map (lambda y: 2*y +1)

Now try to think of the mapping from x's POV. I would love to see map as an
infix operation, e.g.

    map (f, x)	<=>
    f -> x

but that's only syntactic sugar. Imagine an 'operator' |..|, which marks a
sequence argument in an expression and maps the whole expression to it.
So

    result = lambda y: 2*y +1 -> x

would become

    result = 2* |x| +1 		<=>
    result = 2* |1, 2, 3, 4| +1

Of, course a syntactic form like this would be completely unsuitable for a
programming language, because |...| is not an operator but some kind of macro
facility (try to think of rules for combinations of several |...| ).

But it illustrates a view on 'map' which is much easier to deal with - at least
for minds deformed in a similar way to mine..





More information about the Python-list mailing list