There was one more online class I’ve finished. It’s 4-th one. It was Scala and Functional Programming by Martin Odersky.
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(‘/’):
# 2. very bad still imperative ugly solution
regions = reduce(
lambda regions_set, regions_str:
lambda regions_set, region:
regions_set | set((region.strip(),)),
# 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: