Archive

Tag Archives: functional programming

There was one more online class I’ve finished. It’s 4-th one. It was Scala and Functional Programming by Martin Odersky.

Scala

Advertisements

One year ago I’ve posted short note about imperative vs. functional approaches in python. Well, that one was incorrect 😉

The task was to get all unique tokens from several string separated by some delimiter.

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

So, result should be: (‘Some, ST’, ‘More, HERE’, ‘More2, HERE2’)

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

# 2. very bad still imperative ugly solution
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())

# 3. really functional way
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. It’s a pure tool like those from itertools and collections standard python toolsets.

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)

2’nd implementation is still imerative because it provides the result as data. 3-rd approach provides iterator instead. So, real functional programming way is providing not data result but function. Result is something that can be evaluated/calculated to obtain actual result.

Besides, 2-nd code operates by data in its implementation and 3-rd functional code uses only source data (tuple of source strings and separator).

2-nd solution uses functional sugar like lambda, reduce, split, but those ones only made code ugly and huge. Keep in mind, the code should be as small as possible and very clear.

Python has powerful functional tools like iterators and generators; standard packages itertools and collections. So, it’s ok to do some functional programming in python that would be clear, correct and robust.