python hack of the day -- "listable" functions

William Tanksley wtanksle at dolphin.openprojects.net
Thu May 13 16:15:32 EDT 1999


On Thu, 13 May 1999 19:50:35 GMT, Stefan Franke wrote:
>On 12 May 1999 16:30:34 -0700, Michael Vanier <mvanier at bbb.caltech.edu> wrote:

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

[deleted: x = (1,2,3,4)]
>    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 |...| ).

This isn't true -- there are languages which do exactly this.  I think
Icon is one, and I know APL, J, and K are.  As a matter of fact, in all of
those languages the || is implicit, so for example "2*x" does what you
state as "2*|x|" (this makes at least as much sense as Python's
overloading of multiplication for lists).

BTW, though, I'm not sure that || is appropriate.  Mapping isn't an
operation done to a list; it's a modification of the way a function
operates.  In the above example, we're forcing '*' to operate on the
members of the list, we're not changing the list.  Thus, putting
delimiters around the list makes little sense.  How about instead using a
prefix for the parameter to the function, such as '$' (I know, I'm being
flameworthy ;).

2*$x
sum.add($x)
sum.add($(1,2,3,4))

I suppose that this:

y = (1,2,3,$x)

would mean "flatten x into the list", if it means anything.  The only way
it can mean anything is if "," can be thought of as a function, whose
behavior can therefore be modified by $.

$ would be pronounced 'each'; it should be spelled that way too, except
that we don't want to reserve another keyword.

Honestly, though, I'm afraid that none of this is really as good as 'for'
and 'map', when looked at in the traditional Python manner.  In the Python
way of seeing things, a 'map' is the same as a brief 'for' loop; there are
no such things as "adverbs" ($ is an adverb here).

Also, what happens if someone writes "do_something($x,$y)"?

The more I look at this, the more convinced I get that Python shouldn't
try to be J.

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

Play with J.  It's pretty cool.

-- 
-William "Billy" Tanksley
"But you shall not escape my iambics."
           -- Gaius Valerius Catullus




More information about the Python-list mailing list