Advertisement
Lewi7tan

Pipelines in Functional Programming

Jul 8th, 2021
1,686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. from functools import *
  2.  
  3. bands = [{'name': 'sunset rubdown', 'country': 'UK', 'active': False},
  4.          {'name': 'women', 'country': 'Germany', 'active': False},
  5.          {'name': 'a silver mt. zion', 'country': 'Spain', 'active': True}]
  6.  
  7. def assoc(_d, key, value):
  8.     from copy import deepcopy
  9.     d = deepcopy(_d)
  10.     d[key] = value
  11.     return d
  12.  
  13. def call(fn, key): #this one does not do anything
  14.     def apply_fn(record): #this is generated function
  15.         return assoc(record, key, fn(record.get(key))) #record=band
  16.     return apply_fn
  17.  
  18. def pluck(keys):
  19.     def pluck_fn(record):
  20.         return reduce(lambda elements, key: assoc(elements, key, record[key]), keys, {})
  21.     return pluck_fn
  22.  
  23. def pipeline_each(data, functions):
  24.     return reduce(lambda elements, fn: map(fn, elements), #this _elements_ are the data after transformation
  25.                   functions,
  26.                   data)
  27.  
  28. set_canada_as_country = call(lambda x: 'Canada', 'country')
  29. strip_punctuation_from_name = call(lambda x: x.replace('.', ''), 'name')
  30. capitalize_names = call(str.title, 'name')
  31. extract_names_and_countries = pluck(['name', 'country'])
  32.  
  33. new_bands = pipeline_each(bands, [set_canada_as_country,
  34.                                   strip_punctuation_from_name,
  35.                                   capitalize_names,
  36.                                   extract_names_and_countries])
  37.  
  38. for band in new_bands:
  39.     print(band)
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement