Alsuren

May 21, 2008

Cool Python hack

Filed under: Uncategorized — Tags: , , , , — alsuren @ 12:58 am

Some of you might be familiar with python (or haskell, or erlang or …)’s map, filter, and reduce functions. You may also be familiar with lambda expressions, and think that they’re really ugly (especially in python)

If so, check this out (genuine input and output lines from ipython)


In [358]: filter(var==2, [1,2,3,4,5,4,3,2,1])
Out[358]: [2, 2]

In [360]: filter(var>=2, [1,2,3,4,5,4,3,2,1])
Out[361]: [2, 3, 4, 5, 4, 3, 2]

In [363]: filter(var>2, [1,2,3,4,5,4,3,2,1])
Out[362]: [3, 4, 5, 4, 3]

So how did I do it? Well if I could get it to indent correctly then it might look like this:

class Placeholder(object):
    def __lt__(self, other):
        def match(arg):
            return arg < other
        return match
    def __ge__(self, other):
        def match(arg):
            return arg >= other
        return match
    def __le__(self, other):
        def match(arg):
            return arg <= other
        return match
    def __eq__(self, other):
        def match(arg):
            return arg == other
        return match

var=Placeholder()

Now, I *think* this should generalise to map as well, for things like
map(var*5, [1,2,3,4,5,6,5,4,3,2,1] )
just implement __mul__ and friends. Annoyingly, there is also an __rmul__ function, so you don’t know which will be called. Also, don’t let python try to use __cmp__, because it actually checks the type of its return value (so you can’t return a curried function)

Okay, that’s enough g33k for tonight.

[edit: fixed lessthan and greaterthan signs]

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: