Functional Programming Concepts for Imperative Programmers

36
IMPERATIVELY FUNCTIONAL Functional Programming Concepts for Imperative Programmers chris lewis / [email protected] http://twitter.com/burningodzilla http://github.com/chrislewis

description

Inaugural presentation on functional programming for the JaxFunc meetup.

Transcript of Functional Programming Concepts for Imperative Programmers

Page 1: Functional Programming Concepts for Imperative Programmers

IMPERATIVELY FUNCTIONAL

Functional Programming Concepts

for Imperative Programmers

chris lewis / [email protected]://twitter.com/burningodzillahttp://github.com/chrislewis

Page 2: Functional Programming Concepts for Imperative Programmers

Origins: The λ-Calculus

Page 3: Functional Programming Concepts for Imperative Programmers

Origins: The λ-Calculus

Developed at Princeton in the 1930s by Alonzo Church (and others).

Formal system for function definition, application, and recursion.

Not focused on the physical world, but abstract problems about computation.

Page 4: Functional Programming Concepts for Imperative Programmers

Origins: The λ-Calculus

Functions may receive functions as parameters and return functions as results.

A lambda may “close” over free variables to create a closure.

Turing complete.

Page 5: Functional Programming Concepts for Imperative Programmers

Origins: The λ-Calculus

Functions may receive functions as parameters and return functions as results.

A lambda may “close” over free variables to create a closure.

Turing complete.

true := λxy.xfalse := λxy.yif-then-else := λpab.p a b

Page 6: Functional Programming Concepts for Imperative Programmers

Origins: Lisp

Developed at MIT by John McCarthy. An Implementation of the λ-calculus. Uniform treatment of data and functions;

higher-order functions.

Page 7: Functional Programming Concepts for Imperative Programmers

Origins: Lisp

Extensive use of lambda expressions, closures, and recursion.

In Lisp, as any programming language supporting them, lambdas are functions.

Page 8: Functional Programming Concepts for Imperative Programmers

Origins: Lisp(define (is-even? x) (= 0 (modulo x 2)))

(define (when-even x f1 f2) (if (is-even? x) (f1 x) (f2 x)))

(define (down-to-one x) (if (<= x 1) x (down-to-one (- x 1))))

(when-even 4 down-to-one (lambda (x) (+ x 1)))

Page 9: Functional Programming Concepts for Imperative Programmers

There are many facets of functional programming.

We will focus primarily onhigher-order functions and thetreatment of functions as data.

Page 10: Functional Programming Concepts for Imperative Programmers

Functions are Datavar increment = function(i) { return i + 1;}

var square = function(i) { return i * i;}

function doSomething(i, f) { return f(i);}

Page 11: Functional Programming Concepts for Imperative Programmers

Functions are DatadoSomething(5, increment);// -> 6

doSomething(5, square);// -> 25

Page 12: Functional Programming Concepts for Imperative Programmers

Functions are Dataval increment = (i: Int) => i + 1

val square = (i: Int) => i * i

def doSomething[A, B](x: A, f: A => B) = f(x)

doSomething(5, increment)// -> 6

doSomething(5, square)// -> 25

Page 13: Functional Programming Concepts for Imperative Programmers

Notes on Lambdas A lambda is an anonymous function; a

function without an identifier. A closure is a function whose definition

“closes” over free variables.

Page 14: Functional Programming Concepts for Imperative Programmers

Notes on Lambdas A lambda expression that doesn’t close

over free variables isn’t a closure, strictly speaking.

A closure isn’t necessarily anonymous! Closures enable function composition …

… and that’s a big deal!

Page 15: Functional Programming Concepts for Imperative Programmers

λ: In Programming Languages

JavaScript has named and anonymous function expressions, as well as Function objects (with a constructor).

Ruby most notably has blocks, but also lambdas (keyword) and procs!

Scala has methods, function traits, and shorthand yielding trait instances.

How a programming language refers to such a construct is entirely preferential.

Page 16: Functional Programming Concepts for Imperative Programmers

Function Composition

Page 17: Functional Programming Concepts for Imperative Programmers

com·po·si·tion -noun1. the act of combining parts or elements to form a whole2. the resulting state or product3. manner of being composed;structure: This painting has an orderlycomposition.

Page 18: Functional Programming Concepts for Imperative Programmers

com·po·si·tion -noun1. the act of combining parts or elements to form a whole2. the resulting state or product3. manner of being composed;structure: This painting has an orderlycomposition.

Let’s glance back at the math…

Page 19: Functional Programming Concepts for Imperative Programmers

Function Composition

y = f(x) or f: x → y “y is a function of x”

The value of y depends on x; a simple mapping from one value, x, to another, y.

Page 20: Functional Programming Concepts for Imperative Programmers

Function Composition

y = f(x) or f: x → y “y is a function of x”

The value of y depends on x; a simple mapping from one value, x, to another, y.

f: x → y and g: y → z The domains of these functions are

suitable for composition.

Page 21: Functional Programming Concepts for Imperative Programmers

Function Composition

We can combine functions with compatible domains.

Page 22: Functional Programming Concepts for Imperative Programmers

Function Composition

We can combine functions with compatible domains.

(g . f) = g(f(x)) or (g f) = g(f(x))∘ Combine the functions g and f into

a new function that applies g to the result of applying f to x.

Page 23: Functional Programming Concepts for Imperative Programmers

Function Composition

We can combine functions with compatible domains.

(g . f) = g(f(x)) or (g f) = g(f(x))∘ 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!

Page 24: Functional Programming Concepts for Imperative Programmers

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

Page 25: Functional Programming Concepts for Imperative Programmers

In Scala:

def compose[A, B, C](g: B => C, f: A => B) = (x: A) => g(f(x)) // the closure

Page 26: Functional Programming Concepts for Imperative Programmers

Higher-Order Functionsand Lists A function that takes another function as

an argument and/or returns a function as its result.

Ruby, via Rails, brought higher-order functions that operate onlists mainstream.

Higher-order rockstars:each, map, filter, fold many more!

Page 27: Functional Programming Concepts for Imperative Programmers

Because we know how to pass functions around, we know how to implement these …

Page 28: Functional Programming Concepts for Imperative Programmers

Because we know how to pass functions around, we know how to implement these …

… but we’ll probably duplicate code.

Page 29: Functional Programming Concepts for Imperative Programmers

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.

Page 30: Functional Programming Concepts for Imperative Programmers

In JavaScript:

function foldr(list, init, f) { if(list.length == 0) return init; else { return foldr(list.slice(1), f(init, list[0]), f); }}

Page 31: Functional Programming Concepts for Imperative Programmers

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) }

Page 32: Functional Programming Concepts for Imperative Programmers

Some List Functions That can be Defined in Terms of Folding

sum = foldr (+) 0 product = foldr (*) 1 anytrue = foldr ( ) false∨ alltrue = foldr ( ) true∧ map = foldr (cons . f) []

By partially applying folds, we can define new list functions with very little programming!

Page 33: Functional Programming Concepts for Imperative Programmers

Real-World Examples

Higher-order functions pay dividends (strategy pattern, factory, factories of factories, …)

“loan” pattern. Event handling in the Lift framework. List tasks (partitioning, filtering,

transforming).

Page 34: Functional Programming Concepts for Imperative Programmers

What we Didn’t Cover

Currying Pattern matching Type inference, higher-kinded types,

and general type systems Partial function application Monads Lazy vs strict evaluation MORE!

Page 35: Functional Programming Concepts for Imperative Programmers

Questions?

Sample code available at http://github.com/chrislewis/JaxFunc_0_ImperativelyFunctional

Page 36: Functional Programming Concepts for Imperative Programmers

Thanks!

chris lewis / [email protected]://twitter.com/burningodzillahttp://github.com/chrislewis