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(‘/’):

# functional implementation
regions = reduce(
    lambda regions_set, regions_str:
            lambda regions_set, region:
                regions_set | set((region.strip(),)),

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



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)

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: