A place to cache linked articles (think custom and personal wayback machine)
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.md 28KB

4 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. title: A practical introduction to functional programming
  2. url: http://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming
  3. hash_url: 437dce93077f9a2569566bfcfe47134d
  4. <p>Many functional programming articles teach abstract functional techniques. That is, composition, pipelining, higher order functions. This one is different. It shows examples of imperative, unfunctional code that people write every day and translates these examples to a functional style.</p>
  5. <p>The first section of the article takes short, data transforming loops and translates them into functional maps and reduces. The second section takes longer loops, breaks them up into units and makes each unit functional. The third section takes a loop that is a long series of successive data transformations and decomposes it into a functional pipeline.</p>
  6. <p>The examples are in Python, because many people find Python easy to read. A number of the examples eschew pythonicity in order to demonstrate functional techniques common to many languages: map, reduce, pipeline.</p>
  7. <h3>A guide rope</h3>
  8. <p>When people talk about functional programming, they mention a dizzying number of “functional” characteristics. They mention immutable data<sup>1</sup>, first class functions<sup>2</sup> and tail call optimisation<sup>3</sup>. These are language features that aid functional programming. They mention mapping, reducing, pipelining, recursing, currying<sup>4</sup> and the use of higher order functions. These are programming techniques used to write functional code. They mention parallelization<sup>5</sup>, lazy evaluation<sup>6</sup> and determinism<sup>7</sup>. These are advantageous properties of functional programs.</p>
  9. <p>Ignore all that. Functional code is characterised by one thing: the absence of side effects. It doesn’t rely on data outside the current function, and it doesn’t change data that exists outside the current function. Every other “functional” thing can be derived from this property. Use it as a guide rope as you learn.</p>
  10. <p>This is an unfunctional function:</p>
  11. <pre class="prettyprint">&#13;
  12. a = 0&#13;
  13. def increment1():&#13;
  14. global a&#13;
  15. a += 1&#13;
  16. </pre>
  17. <p>This is a functional function:</p>
  18. <pre class="prettyprint">&#13;
  19. def increment2(a):&#13;
  20. return a + 1&#13;
  21. </pre>
  22. <h3>Don’t iterate over lists. Use map and reduce.</h3>
  23. <h4>Map</h4>
  24. <p>Map takes a function and a collection of items. It makes a new, empty collection, runs the function on each item in the original collection and inserts each return value into the new collection. It returns the new collection.</p>
  25. <p>This is a simple map that takes a list of names and returns a list of the lengths of those names:</p>
  26. <pre class="prettyprint">&#13;
  27. name_lengths = map(len, ["Mary", "Isla", "Sam"])&#13;
  28. &#13;
  29. print name_lengths&#13;
  30. # =&gt; [4, 4, 3]&#13;
  31. </pre>
  32. <p>This is a map that squares every number in the passed collection:</p>
  33. <pre class="prettyprint">&#13;
  34. squares = map(lambda x: x * x, [0, 1, 2, 3, 4])&#13;
  35. &#13;
  36. print squares&#13;
  37. # =&gt; [0, 1, 4, 9, 16]&#13;
  38. </pre>
  39. <p>This map doesn’t take a named function. It takes an anonymous, inlined function defined with <code>lambda</code>. The parameters of the lambda are defined to the left of the colon. The function body is defined to the right of the colon. The result of running the function body is (implicitly) returned.</p>
  40. <p>The unfunctional code below takes a list of real names and replaces them with randomly assigned code names.</p>
  41. <pre class="prettyprint">&#13;
  42. import random&#13;
  43. &#13;
  44. names = ['Mary', 'Isla', 'Sam']&#13;
  45. code_names = ['Mr. Pink', 'Mr. Orange', 'Mr. Blonde']&#13;
  46. &#13;
  47. for i in range(len(names)):&#13;
  48. names[i] = random.choice(code_names)&#13;
  49. &#13;
  50. print names&#13;
  51. # =&gt; ['Mr. Blonde', 'Mr. Blonde', 'Mr. Blonde']&#13;
  52. </pre>
  53. <p>(As you can see, this algorithm can potentially assign the same secret code name to multiple secret agents. Hopefully, this won’t be a source of confusion during the secret mission.)</p>
  54. <p>This can be rewritten as a map:</p>
  55. <pre class="prettyprint">&#13;
  56. import random&#13;
  57. &#13;
  58. names = ['Mary', 'Isla', 'Sam']&#13;
  59. &#13;
  60. secret_names = map(lambda x: random.choice(['Mr. Pink',&#13;
  61. 'Mr. Orange',&#13;
  62. 'Mr. Blonde']),&#13;
  63. names)&#13;
  64. </pre>
  65. <p><strong>Exercise 1</strong>. Try rewriting the code below as a map. It takes a list of real names and replaces them with code names produced using a more robust strategy.</p>
  66. <pre class="prettyprint">&#13;
  67. names = ['Mary', 'Isla', 'Sam']&#13;
  68. &#13;
  69. for i in range(len(names)):&#13;
  70. names[i] = hash(names[i])&#13;
  71. &#13;
  72. print names&#13;
  73. # =&gt; [6306819796133686941, 8135353348168144921, -1228887169324443034]&#13;
  74. </pre>
  75. <p>(Hopefully, the secret agents will have good memories and won’t forget each other’s secret code names during the secret mission.)</p>
  76. <p>My solution:</p>
  77. <pre class="prettyprint">&#13;
  78. names = ['Mary', 'Isla', 'Sam']&#13;
  79. &#13;
  80. secret_names = map(hash, names)&#13;
  81. </pre>
  82. <h4>Reduce</h4>
  83. <p>Reduce takes a function and a collection of items. It returns a value that is created by combining the items.</p>
  84. <p>This is a simple reduce. It returns the sum of all the items in the collection.</p>
  85. <pre class="prettyprint">&#13;
  86. sum = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])&#13;
  87. &#13;
  88. print sum&#13;
  89. # =&gt; 10&#13;
  90. </pre>
  91. <p><code>x</code> is the current item being iterated over. <code>a</code> is the accumulator. It is the value returned by the execution of the lambda on the previous item. <code>reduce()</code> walks through the items. For each one, it runs the lambda on the current <code>a</code> and <code>x</code> and returns the result as the <code>a</code> of the next iteration.</p>
  92. <p>What is <code>a</code> in the first iteration? There is no previous iteration result for it to pass along. <code>reduce()</code> uses the first item in the collection for <code>a</code> in the first iteration and starts iterating at the second item. That is, the first <code>x</code> is the second item.</p>
  93. <p>This code counts how often the word <code>'Sam'</code> appears in a list of strings:</p>
  94. <pre class="prettyprint">&#13;
  95. sentences = ['Mary read a story to Sam and Isla.',&#13;
  96. 'Isla cuddled Sam.',&#13;
  97. 'Sam chortled.']&#13;
  98. &#13;
  99. sam_count = 0&#13;
  100. for sentence in sentences:&#13;
  101. sam_count += sentence.count('Sam')&#13;
  102. &#13;
  103. print sam_count&#13;
  104. # =&gt; 3&#13;
  105. </pre>
  106. <p>This is the same code written as a reduce:</p>
  107. <pre class="prettyprint">&#13;
  108. sentences = ['Mary read a story to Sam and Isla.',&#13;
  109. 'Isla cuddled Sam.',&#13;
  110. 'Sam chortled.']&#13;
  111. &#13;
  112. sam_count = reduce(lambda a, x: a + x.count('Sam'),&#13;
  113. sentences,&#13;
  114. 0)&#13;
  115. </pre>
  116. <p>How does this code come up with its initial <code>a</code>? The starting point for the number of incidences of <code>'Sam'</code> cannot be <code>'Mary read a story to Sam and Isla.'</code> The initial accumulator is specified with the third argument to <code>reduce()</code>. This allows the use of a value of a different type from the items in the collection.</p>
  117. <p>Why are map and reduce better?</p>
  118. <p>First, they are often one-liners.</p>
  119. <p>Second, the important parts of the iteration – the collection, the operation and the return value – are always in the same places in every map and reduce.</p>
  120. <p>Third, the code in a loop may affect variables defined before it or code that runs after it. By convention, maps and reduces are functional.</p>
  121. <p>Fourth, map and reduce are elemental operations. Every time a person reads a <code>for</code> loop, they have to work through the logic line by line. There are few structural regularities they can use to create a scaffolding on which to hang their understanding of the code. In contrast, map and reduce are at once building blocks that can be combined into complex algorithms, and elements that the code reader can instantly understand and abstract in their mind. “Ah, this code is transforming each item in this collection. It’s throwing some of the transformations away. It’s combining the remainder into a single output.”</p>
  122. <p>Fifth, map and reduce have many friends that provide useful, tweaked versions of their basic behaviour. For example: <code>filter</code>, <code>all</code>, <code>any</code> and <code>find</code>.</p>
  123. <p><strong>Exercise 2</strong>. Try rewriting the code below using map, reduce and filter. Filter takes a function and a collection. It returns a collection of every item for which the function returned <code>True</code>.</p>
  124. <pre class="prettyprint">&#13;
  125. people = [{'name': 'Mary', 'height': 160},&#13;
  126. {'name': 'Isla', 'height': 80},&#13;
  127. {'name': 'Sam'}]&#13;
  128. &#13;
  129. height_total = 0&#13;
  130. height_count = 0&#13;
  131. for person in people:&#13;
  132. if 'height' in person:&#13;
  133. height_total += person['height']&#13;
  134. height_count += 1&#13;
  135. &#13;
  136. if height_count &gt; 0:&#13;
  137. average_height = height_total / height_count&#13;
  138. &#13;
  139. print average_height&#13;
  140. # =&gt; 120&#13;
  141. </pre>
  142. <p>If this seems tricky, try not thinking about the operations on the data. Think of the states the data will go through, from the list of people dictionaries to the average height. Don’t try and bundle multiple transformations together. Put each on a separate line and assign the result to a descriptively-named variable. Once the code works, condense it.</p>
  143. <p>My solution:</p>
  144. <pre class="prettyprint">&#13;
  145. people = [{'name': 'Mary', 'height': 160},&#13;
  146. {'name': 'Isla', 'height': 80},&#13;
  147. {'name': 'Sam'}]&#13;
  148. &#13;
  149. heights = map(lambda x: x['height'],&#13;
  150. filter(lambda x: 'height' in x, people))&#13;
  151. &#13;
  152. if len(heights) &gt; 0:&#13;
  153. from operator import add&#13;
  154. average_height = reduce(add, heights) / len(heights)&#13;
  155. </pre>
  156. <h3>Write declaratively, not imperatively</h3>
  157. <p>The program below runs a race between three cars. At each time step, each car may move forwards or it may stall. At each time step, the program prints out the paths of the cars so far. After five time steps, the race is over.</p>
  158. <p>This is some sample output:</p>
  159. <pre class="prettyprint">&#13;
  160. -&#13;
  161. --&#13;
  162. --&#13;
  163. &#13;
  164. --&#13;
  165. --&#13;
  166. ---&#13;
  167. &#13;
  168. ---&#13;
  169. --&#13;
  170. ---&#13;
  171. &#13;
  172. ----&#13;
  173. ---&#13;
  174. ----&#13;
  175. &#13;
  176. ----&#13;
  177. ----&#13;
  178. -----&#13;
  179. </pre>
  180. <p>This is the program:</p>
  181. <pre class="prettyprint">&#13;
  182. from random import random&#13;
  183. &#13;
  184. time = 5&#13;
  185. car_positions = [1, 1, 1]&#13;
  186. &#13;
  187. while time:&#13;
  188. # decrease time&#13;
  189. time -= 1&#13;
  190. &#13;
  191. print ''&#13;
  192. for i in range(len(car_positions)):&#13;
  193. # move car&#13;
  194. if random() &gt; 0.3:&#13;
  195. car_positions[i] += 1&#13;
  196. &#13;
  197. # draw car&#13;
  198. print '-' * car_positions[i]&#13;
  199. </pre>
  200. <p>The code is written imperatively. A functional version would be declarative. It would describe what to do, rather than how to do it.</p>
  201. <h4>Use functions</h4>
  202. <p>A program can be made more declarative by bundling pieces of the code into functions.</p>
  203. <pre class="prettyprint">&#13;
  204. from random import random&#13;
  205. &#13;
  206. def move_cars():&#13;
  207. for i, _ in enumerate(car_positions):&#13;
  208. if random() &gt; 0.3:&#13;
  209. car_positions[i] += 1&#13;
  210. &#13;
  211. def draw_car(car_position):&#13;
  212. print '-' * car_position&#13;
  213. &#13;
  214. def run_step_of_race():&#13;
  215. global time&#13;
  216. time -= 1&#13;
  217. move_cars()&#13;
  218. &#13;
  219. def draw():&#13;
  220. print ''&#13;
  221. for car_position in car_positions:&#13;
  222. draw_car(car_position)&#13;
  223. &#13;
  224. time = 5&#13;
  225. car_positions = [1, 1, 1]&#13;
  226. &#13;
  227. while time:&#13;
  228. run_step_of_race()&#13;
  229. draw()&#13;
  230. </pre>
  231. <p>To understand this program, the reader just reads the main loop. “If there is time left, run a step of the race and draw. Check the time again.” If the reader wants to understand more about what it means to run a step of the race, or draw, they can read the code in those functions.</p>
  232. <p>There are no comments any more. The code describes itself.</p>
  233. <p>Splitting code into functions is a great, low brain power way to make code more readable.</p>
  234. <p>This technique uses functions, but it uses them as sub-routines. They parcel up code. The code is not functional in the sense of the guide rope. The functions in the code use state that was not passed as arguments. They affect the code around them by changing external variables, rather than by returning values. To check what a function really does, the reader must read each line carefully. If they find an external variable, they must find its origin. They must see what other functions change that variable.</p>
  235. <h4>Remove state</h4>
  236. <p>This is a functional version of the car race code:</p>
  237. <pre class="prettyprint">&#13;
  238. from random import random&#13;
  239. &#13;
  240. def move_cars(car_positions):&#13;
  241. return map(lambda x: x + 1 if random() &gt; 0.3 else x,&#13;
  242. car_positions)&#13;
  243. &#13;
  244. def output_car(car_position):&#13;
  245. return '-' * car_position&#13;
  246. &#13;
  247. def run_step_of_race(state):&#13;
  248. return {'time': state['time'] - 1,&#13;
  249. 'car_positions': move_cars(state['car_positions'])}&#13;
  250. &#13;
  251. def draw(state):&#13;
  252. print ''&#13;
  253. print '\n'.join(map(output_car, state['car_positions']))&#13;
  254. &#13;
  255. def race(state):&#13;
  256. draw(state)&#13;
  257. if state['time']:&#13;
  258. race(run_step_of_race(state))&#13;
  259. &#13;
  260. race({'time': 5,&#13;
  261. 'car_positions': [1, 1, 1]})&#13;
  262. </pre>
  263. <p>The code is still split into functions, but the functions are functional. There are three signs of this. First, there are no longer any shared variables. <code>time</code> and <code>car_positions</code> get passed straight into <code>race()</code>. Second, functions take parameters. Third, no variables are instantiated inside functions. All data changes are done with return values. <code>race()</code> recurses<sup>3</sup> with the result of <code>run_step_of_race()</code>. Each time a step generates a new state, it is passed immediately into the next step.</p>
  264. <p>Now, here are two functions, <code>zero()</code> and <code>one()</code>:</p>
  265. <pre class="prettyprint">&#13;
  266. def zero(s):&#13;
  267. if s[0] == "0":&#13;
  268. return s[1:]&#13;
  269. &#13;
  270. def one(s):&#13;
  271. if s[0] == "1":&#13;
  272. return s[1:]&#13;
  273. </pre>
  274. <p><code>zero()</code> takes a string, <code>s</code>. If the first character is <code>'0'</code>, it returns the rest of the string. If it is not, it returns <code>None</code>, the default return value of Python functions. <code>one()</code> does the same, but for a first character of <code>'1'</code>.</p>
  275. <p>Imagine a function called <code>rule_sequence()</code>. It takes a string and a list of rule functions of the form of <code>zero()</code> and <code>one()</code>. It calls the first rule on the string. Unless <code>None</code> is returned, it takes the return value and calls the second rule on it. Unless <code>None</code> is returned, it takes the return value and calls the third rule on it. And so forth. If any rule returns <code>None</code>, <code>rule_sequence()</code> stops and returns <code>None</code>. Otherwise, it returns the return value of the final rule.</p>
  276. <p>This is some sample input and output:</p>
  277. <pre class="prettyprint">&#13;
  278. print rule_sequence('0101', [zero, one, zero])&#13;
  279. # =&gt; 1&#13;
  280. &#13;
  281. print rule_sequence('0101', [zero, zero])&#13;
  282. # =&gt; None&#13;
  283. </pre>
  284. <p>This is the imperative version of <code>rule_sequence()</code>:</p>
  285. <pre class="prettyprint">&#13;
  286. def rule_sequence(s, rules):&#13;
  287. for rule in rules:&#13;
  288. s = rule(s)&#13;
  289. if s == None:&#13;
  290. break&#13;
  291. &#13;
  292. return s&#13;
  293. </pre>
  294. <p><strong>Exercise 3</strong>. The code above uses a loop to do its work. Make it more declarative by rewriting it as a recursion.</p>
  295. <p>My solution:</p>
  296. <pre class="prettyprint">&#13;
  297. def rule_sequence(s, rules):&#13;
  298. if s == None or not rules:&#13;
  299. return s&#13;
  300. else:&#13;
  301. return rule_sequence(rules[0](s), rules[1:])&#13;
  302. </pre>
  303. <h3>Use pipelines</h3>
  304. <p>In the previous section, some imperative loops were rewritten as recursions that called out to auxiliary functions. In this section, a different type of imperative loop will be rewritten using a technique called a pipeline.</p>
  305. <p>The loop below performs transformations on dictionaries that hold the name, incorrect country of origin and active status of some bands.</p>
  306. <pre class="prettyprint">&#13;
  307. bands = [{'name': 'sunset rubdown', 'country': 'UK', 'active': False},&#13;
  308. {'name': 'women', 'country': 'Germany', 'active': False},&#13;
  309. {'name': 'a silver mt. zion', 'country': 'Spain', 'active': True}]&#13;
  310. &#13;
  311. def format_bands(bands):&#13;
  312. for band in bands:&#13;
  313. band['country'] = 'Canada'&#13;
  314. band['name'] = band['name'].replace('.', '')&#13;
  315. band['name'] = band['name'].title()&#13;
  316. &#13;
  317. format_bands(bands)&#13;
  318. &#13;
  319. print bands&#13;
  320. # =&gt; [{'name': 'Sunset Rubdown', 'active': False, 'country': 'Canada'},&#13;
  321. # {'name': 'Women', 'active': False, 'country': 'Canada' },&#13;
  322. # {'name': 'A Silver Mt Zion', 'active': True, 'country': 'Canada'}]&#13;
  323. </pre>
  324. <p>Worries are stirred by the name of the function. “format” is very vague. Upon closer inspection of the code, these worries begin to claw. Three things happen in the same loop. The <code>'country'</code> key gets set to <code>'Canada'</code>. Punctuation is removed from the band name. The band name gets capitalized. It is hard to tell what the code is intended to do and hard to tell if it does what it appears to do. The code is hard to reuse, hard to test and hard to parallelize.</p>
  325. <p>Compare it with this:</p>
  326. <pre class="prettyprint">&#13;
  327. print pipeline_each(bands, [set_canada_as_country,&#13;
  328. strip_punctuation_from_name,&#13;
  329. capitalize_names])&#13;
  330. </pre>
  331. <p>This code is easy to understand. It gives the impression that the auxiliary functions are functional because they seem to be chained together. The output from the previous one comprises the input to the next. If they are functional, they are easy to verify. They are also easy to reuse, easy to test and easy to parallelize.</p>
  332. <p>The job of <code>pipeline_each()</code> is to pass the bands, one at a time, to a transformation function, like <code>set_canada_as_country()</code>. After the function has been applied to all the bands, <code>pipeline_each()</code> bundles up the transformed bands. Then, it passes each one to the next function.</p>
  333. <p>Let’s look at the transformation functions.</p>
  334. <pre class="prettyprint">&#13;
  335. def assoc(_d, key, value):&#13;
  336. from copy import deepcopy&#13;
  337. d = deepcopy(_d)&#13;
  338. d[key] = value&#13;
  339. return d&#13;
  340. &#13;
  341. def set_canada_as_country(band):&#13;
  342. return assoc(band, 'country', "Canada")&#13;
  343. &#13;
  344. def strip_punctuation_from_name(band):&#13;
  345. return assoc(band, 'name', band['name'].replace('.', ''))&#13;
  346. &#13;
  347. def capitalize_names(band):&#13;
  348. return assoc(band, 'name', band['name'].title())&#13;
  349. </pre>
  350. <p>Each one associates a key on a band with a new value. There is no easy way to do this without mutating the original band. <code>assoc()</code> solves this problem by using <code>deepcopy()</code> to produce a copy of the passed dictionary. Each transformation function makes its modification to the copy and returns that copy.</p>
  351. <p>Everything seems fine. Band dictionary originals are protected from mutation when a key is associated with a new value. But there are two other potential mutations in the code above. In <code>strip_punctuation_from_name()</code>, the unpunctuated name is generated by calling <code>replace()</code> on the original name. In <code>capitalize_names()</code>, the capitalized name is generated by calling <code>title()</code> on the original name. If <code>replace()</code> and <code>title()</code> are not functional, <code>strip_punctuation_from_name()</code> and <code>capitalize_names()</code> are not functional.</p>
  352. <p>Fortunately, <code>replace()</code> and <code>title()</code> do not mutate the strings they operate on. This is because strings are immutable in Python. When, for example, <code>replace()</code> operates on a band name string, the original band name is copied and <code>replace()</code> is called on the copy. Phew.</p>
  353. <p>This contrast between the mutability of strings and dictionaries in Python illustrates the appeal of languages like Clojure. The programmer need never think about whether they are mutating data. They aren’t.</p>
  354. <p><strong>Exercise 4</strong>. Try and write the <code>pipeline_each</code> function. Think about the order of operations. The bands in the array are passed, one band at a time, to the first transformation function. The bands in the resulting array are passed, one band at a time, to the second transformation function. And so forth.</p>
  355. <p>My solution:</p>
  356. <pre class="prettyprint">&#13;
  357. def pipeline_each(data, fns):&#13;
  358. return reduce(lambda a, x: map(x, a),&#13;
  359. fns,&#13;
  360. data)&#13;
  361. </pre>
  362. <p>All three transformation functions boil down to making a change to a particular field on the passed band. <code>call()</code> can be used to abstract that. It takes a function to apply and the key of the value to apply it to.</p>
  363. <pre class="prettyprint">&#13;
  364. set_canada_as_country = call(lambda x: 'Canada', 'country')&#13;
  365. strip_punctuation_from_name = call(lambda x: x.replace('.', ''), 'name')&#13;
  366. capitalize_names = call(str.title, 'name')&#13;
  367. &#13;
  368. print pipeline_each(bands, [set_canada_as_country,&#13;
  369. strip_punctuation_from_name,&#13;
  370. capitalize_names])&#13;
  371. </pre>
  372. <p>Or, if we are willing to sacrifice readability for conciseness, just:</p>
  373. <pre class="prettyprint">&#13;
  374. print pipeline_each(bands, [call(lambda x: 'Canada', 'country'),&#13;
  375. call(lambda x: x.replace('.', ''), 'name'),&#13;
  376. call(str.title, 'name')])&#13;
  377. </pre>
  378. <p>The code for <code>call()</code>:</p>
  379. <pre class="prettyprint">&#13;
  380. def assoc(_d, key, value):&#13;
  381. from copy import deepcopy&#13;
  382. d = deepcopy(_d)&#13;
  383. d[key] = value&#13;
  384. return d&#13;
  385. &#13;
  386. def call(fn, key):&#13;
  387. def apply_fn(record):&#13;
  388. return assoc(record, key, fn(record.get(key)))&#13;
  389. return apply_fn&#13;
  390. </pre>
  391. <p>There is a lot going on here. Let’s take it piece by piece.</p>
  392. <p>One. <code>call()</code> is a higher order function. A higher order function takes a function as an argument, or returns a function. Or, like <code>call()</code>, it does both.</p>
  393. <p>Two. <code>apply_fn()</code> looks very similar to the three transformation functions. It takes a record (a band). It looks up the value at <code>record[key]</code>. It calls <code>fn</code> on that value. It assigns the result back to a copy of the record. It returns the copy.</p>
  394. <p>Three. <code>call()</code> does not do any actual work. <code>apply_fn()</code>, when called, will do the work. In the example of using <code>pipeline_each()</code> above, one instance of <code>apply_fn()</code> will set <code>'country'</code> to <code>'Canada'</code> on a passed band. Another instance will capitalize the name of a passed band.</p>
  395. <p>Four. When an <code>apply_fn()</code> instance is run, <code>fn</code> and <code>key</code> will not be in scope. They are neither arguments to <code>apply_fn()</code>, nor locals inside it. But they will still be accessible. When a function is defined, it saves references to the variables it closes over: those that were defined in a scope outside the function and that are used inside the function. When the function is run and its code references a variable, Python looks up the variable in the locals and in the arguments. If it doesn’t find it there, it looks in the saved references to closed over variables. This is where it will find <code>fn</code> and <code>key</code>.</p>
  396. <p>Five. There is no mention of bands in the <code>call()</code> code. That is because <code>call()</code> could be used to generate pipeline functions for any program, regardless of topic. Functional programming is partly about building up a library of generic, reusable, composable functions.</p>
  397. <p>Good job. Closures, higher order functions and variable scope all covered in the space of a few paragraphs. Have a nice glass of lemonade.</p>
  398. <p>There is one more piece of band processing to do. That is to remove everything but the name and country. <code>extract_name_and_country()</code> can pull that information out:</p>
  399. <pre class="prettyprint">&#13;
  400. def extract_name_and_country(band):&#13;
  401. plucked_band = {}&#13;
  402. plucked_band['name'] = band['name']&#13;
  403. plucked_band['country'] = band['country']&#13;
  404. return plucked_band&#13;
  405. &#13;
  406. print pipeline_each(bands, [call(lambda x: 'Canada', 'country'),&#13;
  407. call(lambda x: x.replace('.', ''), 'name'),&#13;
  408. call(str.title, 'name'),&#13;
  409. extract_name_and_country])&#13;
  410. &#13;
  411. # =&gt; [{'name': 'Sunset Rubdown', 'country': 'Canada'},&#13;
  412. # {'name': 'Women', 'country': 'Canada'},&#13;
  413. # {'name': 'A Silver Mt Zion', 'country': 'Canada'}]&#13;
  414. </pre>
  415. <p><code>extract_name_and_country()</code> could have been written as a generic function called <code>pluck()</code>. <code>pluck()</code> would be used like this:</p>
  416. <pre class="prettyprint">&#13;
  417. print pipeline_each(bands, [call(lambda x: 'Canada', 'country'),&#13;
  418. call(lambda x: x.replace('.', ''), 'name'),&#13;
  419. call(str.title, 'name'),&#13;
  420. pluck(['name', 'country'])])&#13;
  421. </pre>
  422. <p><strong>Exercise 5</strong>. <code>pluck()</code> takes a list of keys to extract from each record. Try and write it. It will need to be a higher order function.</p>
  423. <p>My solution:</p>
  424. <pre class="prettyprint">&#13;
  425. def pluck(keys):&#13;
  426. def pluck_fn(record):&#13;
  427. return reduce(lambda a, x: assoc(a, x, record[x]),&#13;
  428. keys,&#13;
  429. {})&#13;
  430. return pluck_fn&#13;
  431. </pre>
  432. <h3>What now?</h3>
  433. <p>Functional code co-exists very well with code written in other styles. The transformations in this article can be applied to any code base in any language. Try applying them to your own code.</p>
  434. <p>Think of Mary, Isla and Sam. Turn iterations of lists into maps and reduces.</p>
  435. <p>Think of the race. Break code into functions. Make those functions functional. Turn a loop that repeats a process into a recursion.</p>
  436. <p>Think of the bands. Turn a sequence of operations into a pipeline.</p>
  437. <p><br/></p>
  438. <p><sup>1</sup> An immutable piece of data is one that cannot be changed. Some languages, like Clojure, make all values immutable by default. Any “mutating” operations copy the value, change it and pass back the changed copy. This eliminates bugs that arise from a programmer’s incomplete model of the possible states their program may enter.</p>
  439. <p><sup>2</sup> Languages that support first class functions allow functions to be treated like any other value. This means they can be created, passed to functions, returned from functions and stored inside data structures.</p>
  440. <p><sup>3</sup> Tail call optimisation is a programming language feature. Each time a function recurses, a new stack frame is created. A stack frame is used to store the arguments and local values for the current function invocation. If a function recurses a large number of times, it is possible for the interpreter or compiler to run out of memory. Languages with tail call optimisation reuse the same stack frame for their entire sequence of recursive calls. Languages like Python that do not have tail call optimisation generally limit the number of times a function may recurse to some number in the thousands. In the case of the <code>race()</code> function, there are only five time steps, so it is safe.</p>
  441. <p><sup>4</sup> Currying means decomposing a function that takes multiple arguments into a function that takes the first argument and returns a function that takes the next argument, and so forth for all the arguments.</p>
  442. <p><sup>5</sup> Parallelization means running the same code concurrently without synchronization. These concurrent processes are often run on multiple processors.</p>
  443. <p><sup>6</sup> Lazy evaluation is a compiler technique that avoids running code until the result is needed.</p>
  444. <p><sup>7</sup> A process is deterministic if repetitions yield the same result every time.</p>