Sunday, May 17, 2015

Intro to Higher Order Functions

"Plucking the grass to know where sits the wind"
-- Shakespeare, The Merchant of Venice
Act I, Scene I, Line 19

Intro


Step on up.  Come one, come all. See the amazing function which produces other functions.  See the marvelous function which consumes other functions.  See things which you will tell your grandkids about.

Functions Producing Functions


Our first sight is the amazing function which produces other functions.

function A produces function B


In JavaScript and Clojure we would have the following:



We see in repl.js that we are having a return b which returns the string 'Bilbo'.  Likewise in repl_es6.js we see the first lambda return another lambda which returns the string 'Bilbo'.  In repl.clj we see the function a returns the function b which returns the string "Bilbo".  Three examples of a function producing another function.

Functions Consuming Functions


Our next sight is a function which consumes another function.

function A consumes function B


In JavaScript and Clojure we would have the following:



We see in repl.js that we are having function a consume function b which when invoked returns the string 'Bilbo'.  Likewise in repl_es6.js we see the first lambda consumes the lambda passed in which when invoked returns the string 'Bilbo'.  In repl.clj we see the function a consumes the function b which when invoked returns the string "Bilbo".  Three examples of a function consuming another function.

Pluck


The next sight we see Pluck taking apart a dwarf.



In JavaScript and Clojure we would have the following:



We see in repl.js and repl_es6.js we can use lodash's Pluck function extract the name property from our dwarves.  Likewise in repl.clj we can use the Map function with the :name keyword to extract the name value form our dwarves.

Reduce


This last sight to see is a function which will Reduce its input to a single value.



In JavaScript and Clojure we would have the following:



In repl.js and repl_es6.js we can use lodash's Reduce / Foldl function to sum up the values of 1, 2, 3, and 4 to get the value of 10, we can leave out the seed value and still get 10, or we can use a seed value of 100 to get 110.  Likewise in repl.clj we can use the Reduce function to sum up the values of 1, 2, 3, and 4 to get again 10, we can also not give a seed value or given it a different value just as before.

Fin


Thank you and watch your step on the way out.