Archive

Monthly Archives: February 2011

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)

Several weeks ago I’ve done simple PHP AJAX editor of dummy strings list. It was test task for the interview. There are list of strings saved in MySQL table and AJAX CRUD web interface.

The most fun point was a condition to avoid any JS or PHP framework. It means pure PHP and pure JS, as I understand, just to test coding skills. I realized that I’m using different frameworks for already long period of time. I can’t imagine myself coding without jQuery, for example. I remember those times but it was so long time ago…

Here is my implementation of example composed into single file: single_file.php