14. There are many facets of functional programming.We will focus primarily onhigher-order functions and thetreatment of functions as data.
15. Functions are Data varincrement = function(i) { return i + 1; } varsquare = function(i) { return i * i; } function doSomething(i, f) { return f(i); }
16. Functions are Data doSomething(5, increment); // -> 6 doSomething(5, square); // -> 25
17. Functions are Data valincrement = (i: Int) => i + 1 valsquare = (i: Int) => i * i def doSomething[A, B](x: A, f: A => B) = f(x) doSomething(5, increment) // -> 6 doSomething(5, square) // -> 25
36. Combine the functions g and f into a new function that applies g to the result of applying f to x.Back to the code!
37. In JavaScript: function compose(f, g) { // a closure, closing over the free // variables f and g return function(x) { return g(f(x)); } } // recursive implementation: // http://gist.github.com/366614
38. In Scala: def compose[A, B, C](g: B => C, f: A => B) = (x: A) => g(f(x)) // the closure
39.
40. Ruby, via Rails, brought higher-order functions that operate onlists mainstream.
41.
42. Because we know how to pass functions around, we know how to implement these …… but we’ll probably duplicate code.
43. Because we know how to pass functions around, we know how to implement these …… but we’ll probably duplicate code.Let’s talk about folding.
45. In Scala: def foldr[A, B](list: List[A], init: B, f: (B, A) => B): B = list match { case Nil => init case head :: tail => foldr(tail, f(init, head), f) }