Python: imperative vs. functional

Almost any modern mainstream imperative programming language has some stuff of functional programming.
But not all of them are really cool.
E.g., LINQ looks very nice in .NET world. After several years of practice it drives like something native, as it was from the begining of time.
Conversely, I don’t feel the same at line of python.

# Get unique set of regions from the several sources. There are regions in the strings.

regions_strs = (“Some, ST / More, HERE”, “Some, ST / More2, HERE2”)

# imperative implementation
regions = set()
for s in regions_strs:
    for token in s.split(‘/’):
        regions.add(token.strip())

# functional implementation
regions = reduce(
    lambda regions_set, regions_str:
        reduce(
            lambda regions_set, region:
                regions_set | set((region.strip(),)),
            regions_str.split(‘/’),
            regions_set),
    regions_strs,
    set())

As you can see imperative implementation is much more clear and compact.

 

UPDATE:

Well, for now (one year later) I have a bit clear and simple really functional solution:

unique_regions = iunique(token.strip() for token in    itertools.chain(*(s.split('/') for s in regions_strs)))

where iunique is a special generator that used as filter for abstract iterator

def iunique(iterable, key=lambda x: x):        """ unique filter """        seen = set()        for elem, ekey in ((e, key(e)) for e in iterable):                if ekey not in seen:                        yield elem                        seen.add(ekey)
Advertisements

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

%d bloggers like this: