Code block literals

Sean Ross sross at connectmail.carleton.ca
Mon Oct 13 11:14:32 EDT 2003


"John Roth" <newsgroups at jhrothjr.com> wrote in message
news:vol02ieh5inade at news.supernews.com...
>
> foobar = map(| x, y, z |
>         astatement
>         anotherstatement
>     list1, list2, list3)
>
> I kind of like this better, except for one really unfortunate


Hi.
There was a short discussion along these lines back in June where I
mentioned the idea of using thunks, or something like that
http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&selm=vwsLa.7927%24OE2.1069377%40news20.bellglobal.com

The idea goes something like this:

Let's take imap as an example

  def imap(function, *iterables):
         iterables = map(iter, iterables)
         while True:
             args = [i.next() for i in iterables]
             if function is None:
                 yield tuple(args)
             else:
                 yield function(*args)


Here, you would use imap as follows:

mapped = imap(lambda x: x*x, sequence)

My idea would be to define imap as follows:

  def imap(&function, *iterables):
         iterables = map(iter, iterables)
         while True:
             args = [i.next() for i in iterables]
             if function is None:
                 yield tuple(args)
             else:
                 yield function(*args)

and the use could be more like this:

mapped = imap(sequence) with x:
        print x  # or whatever
        return x*x

with x: ... creates a thunk, or anonymous function, which will be fed as an
argument to the imap function in place of the &function parameter.

I also had some hazy notion of having a two way feed. Where a thunk that is
associated with an iterator function could be fed arguments, and executed on
each iteration. Something like this:

y = 0
itertools.count(10) do with x:
        y += x
print y


Anyway. I was thinking that the foobar example would look cleaner if the
block did not have to be included directly as an argument to the function
call, but could instead be associated with the function call, tacked onto
the end, like so

 foobar = map(list1, list2, list3) with x, y, z:
        astatement
        anotherstatement

or maybe

 foobar = map(list1, list2, list3) { (x, y, z):
        astatement
        anotherstatement
}

or, if we want to be explicit:

 foobar = map(&thunk, list1, list2, list3) with x, y, z:
        astatement
        anotherstatement

so that we know where the thunk is being fed to as an argument. But, this
would probably limit the number of blocks you could pass to a function.

Anyway, as I've said, these are just some fuzzy little notions I've had in
passing. I'm not advocating their inclusion in the language or anything like
that.  I just thought I'd mention them in case they're of some use, even if
they're just something to point to and say, "we definitely don't want that".

Sean














More information about the Python-list mailing list