Share
Embed
A (Somewhat Gentle) Introduction to Functional Programming
A short talk I gave recently introducing Functional Programming.
Some of the discussion was done free form hence not 100% "web friendly" slides, but feel free to forward questions to me.
Brendan McAdams
March 03, 2012
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
94 slides
-
Brendan McAdams 10gen, Inc. [email protected] @rit “Functions All The Way
Down” A (Somewhat Gentle) Introduction to Functional Programming -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept • Rooted in the concepts of Lambda Calculus (~1930s) -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept • Rooted in the concepts of Lambda Calculus (~1930s) • Introduced in many early languages such as Lisp -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept • Rooted in the concepts of Lambda Calculus (~1930s) • Introduced in many early languages such as Lisp • Recently undergoing a renaissance -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept • Rooted in the concepts of Lambda Calculus (~1930s) • Introduced in many early languages such as Lisp • Recently undergoing a renaissance • Functional Languages like Haskell, Clojure and Scala gaining popularity as “real” tools -
Everything That’s Old Is New Again... • Functional Programming is
far from a new concept • Rooted in the concepts of Lambda Calculus (~1930s) • Introduced in many early languages such as Lisp • Recently undergoing a renaissance • Functional Languages like Haskell, Clojure and Scala gaining popularity as “real” tools • Traditionally imperative languages such as C++ are gaining concepts from functional languages in recent revisions -
Everything That’s Old Is New Again... • We improve ourselves
and our code by learning from & leveraging FP -
Everything That’s Old Is New Again... • We improve ourselves
and our code by learning from & leveraging FP • Avoiding Mutable values and State for referential transparency -
Everything That’s Old Is New Again... • We improve ourselves
and our code by learning from & leveraging FP • Avoiding Mutable values and State for referential transparency • Using functions as a higher level concept for composition -
Everything That’s Old Is New Again... • We improve ourselves
and our code by learning from & leveraging FP • Avoiding Mutable values and State for referential transparency • Using functions as a higher level concept for composition • ... and thinking in terms of functions being closer to the composable, reusable units they are meant to be -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) • This is by no means a comprehensive course on functional programming -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) • This is by no means a comprehensive course on functional programming • If you like what you see, I recommend a few books -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) • This is by no means a comprehensive course on functional programming • If you like what you see, I recommend a few books • “Learn You A Haskell For Great Good” (Lightweight & lighthearted) -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) • This is by no means a comprehensive course on functional programming • If you like what you see, I recommend a few books • “Learn You A Haskell For Great Good” (Lightweight & lighthearted) • “The Little Schemer” (if you like Lisp) -
Everything That’s Old Is New Again... • I am going
to introduce some functional programming (as well as a little bit of my favorite language for it, Scala) • This is by no means a comprehensive course on functional programming • If you like what you see, I recommend a few books • “Learn You A Haskell For Great Good” (Lightweight & lighthearted) • “The Little Schemer” (if you like Lisp) • “Real World Haskell” (heavy and in depth, if you want a real dive) -
What is this? int multiply(int x, int y) { return
x * y; } That’s right... it’s a function (in C/C++) -
What is this? int multiply(int x, int y) { return
x * y; } That’s right... it’s a function (in C/C++) We can invoke it to calculate a value... -
What is this? int multiply(int x, int y) { return
x * y; } That’s right... it’s a function (in C/C++) We can invoke it to calculate a value... int main() { int x = 512000; int y = 128; int z = multiply(x, y); std::cout << x << "*" << y << " is: " << z << std::endl; } -
Python shouldn’t be too different... def multiply(x, y): return x
* y if __name__ == '__main__': x = 512000 y = 128 z = multiply(x, y) print "%i*%i is %i" % (x, y, z) -
Python shouldn’t be too different... def multiply(x, y): return x
* y if __name__ == '__main__': x = 512000 y = 128 z = multiply(x, y) print "%i*%i is %i" % (x, y, z) Python has some FP influence though... -
Python shouldn’t be too different... def multiply(x, y): return x
* y if __name__ == '__main__': x = 512000 y = 128 z = multiply(x, y) print "%i*%i is %i" % (x, y, z) Python has some FP influence though... print "Multiply Function: %s" % multiply # Multiply Function: <function multiply at 0x1101ef938> foobar = multiply print "%i*%i is %i" % (x, y, foobar(x, y)) -
First Class Functions • These tricks work because Python considers
functions to be “first class” -
First Class Functions • These tricks work because Python considers
functions to be “first class” • a function named “multiply” is simply a variable of type “function” -
First Class Functions • These tricks work because Python considers
functions to be “first class” • a function named “multiply” is simply a variable of type “function” • Technically you can use pointers to do similar tricks in C/C++ but it’s far from easy (or transparent) -
First Class Functions • These tricks work because Python considers
functions to be “first class” • a function named “multiply” is simply a variable of type “function” • Technically you can use pointers to do similar tricks in C/C++ but it’s far from easy (or transparent) • Many languages segregate function as if they are special, meaning they are not truly composable units of work. -
First Class Functions • These tricks work because Python considers
functions to be “first class” • a function named “multiply” is simply a variable of type “function” • Technically you can use pointers to do similar tricks in C/C++ but it’s far from easy (or transparent) • Many languages segregate function as if they are special, meaning they are not truly composable units of work. • In FP, we try to leverage the function as just another tool - meaning it must be flexible, reusable and first class. -
Let’s Look at Scala • Python is not truly functional,
but instead borrows some concepts of functional programming -
Let’s Look at Scala • Python is not truly functional,
but instead borrows some concepts of functional programming • Instead, let’s look at Scala... which is a true blend of Object Oriented + Functional programming with a full arsenal of FP tools. -
Let’s Look at Scala • Python is not truly functional,
but instead borrows some concepts of functional programming • Instead, let’s look at Scala... which is a true blend of Object Oriented + Functional programming with a full arsenal of FP tools. • Scala was created by Martin Odersky (author of Java Generics & the 1.5+ javac) at EPFL in Switzlerand -
Let’s Look at Scala • Python is not truly functional,
but instead borrows some concepts of functional programming • Instead, let’s look at Scala... which is a true blend of Object Oriented + Functional programming with a full arsenal of FP tools. • Scala was created by Martin Odersky (author of Java Generics & the 1.5+ javac) at EPFL in Switzlerand • JVM based, able to interoperate cleanly with Java & existing libraries -
Let’s Look at Scala • Python is not truly functional,
but instead borrows some concepts of functional programming • Instead, let’s look at Scala... which is a true blend of Object Oriented + Functional programming with a full arsenal of FP tools. • Scala was created by Martin Odersky (author of Java Generics & the 1.5+ javac) at EPFL in Switzlerand • JVM based, able to interoperate cleanly with Java & existing libraries • Used by companies such as Twitter, Foursquare, The Guardian, LinkedIn, and many more -
First Class Functions in Scala def multiply(x: Int, y: Int)
= { x * y } val n = 512000 val o = 128 val p = multiply(n, o) println("%s*%s is %s".format(n, o, p)) // 512000*128 is 65536000 println("Multiply Function: %s".format(multiply _)) val foobar = multiply _ // Multiply Function: <function2> println("%s*%s is %s".format(n, o, foobar(n, o))) // 512000*128 is 65536000 -
Going Anonymous • If a function is a truly composable
& reusable unit, we should also be able to define it ‘anonymously’ -
Going Anonymous • If a function is a truly composable
& reusable unit, we should also be able to define it ‘anonymously’ • This concept is sometimes referred to as lambdas -
Going Anonymous • If a function is a truly composable
& reusable unit, we should also be able to define it ‘anonymously’ • This concept is sometimes referred to as lambdas • Lambdas are one of the most borrowed FP concepts in traditional languages -
Going Anonymous • If a function is a truly composable
& reusable unit, we should also be able to define it ‘anonymously’ • This concept is sometimes referred to as lambdas • Lambdas are one of the most borrowed FP concepts in traditional languages • In some cases, Lambdas exist exclusively of “first class” functions (but can be used to tackle similar needs) -
Anonymous Functions / Lambdas In Scala val multiply = (x:
Int, y: Int) => { x * y } val n = 512000 val o = 128 val p = multiply(n, o) println("%s*%s is %s".format(n, o, p)) // 512000*128 is 65536000 -
Anonymous Functions in Other Languages • Python has Lambdas as
well (but restricts to one liners) -
Anonymous Functions in Other Languages • Python has Lambdas as
well (but restricts to one liners) lambda x, y: x * y # <function <lambda> at 0x10acce938> multiply = lambda x, y: x * y multiply(5, 2) # 10 -
Anonymous Functions in Other Languages • Python has Lambdas as
well (but restricts to one liners) • C++ 11 is even adding them to C++! lambda x, y: x * y # <function <lambda> at 0x10acce938> multiply = lambda x, y: x * y multiply(5, 2) # 10 -
Anonymous Functions in Other Languages • Python has Lambdas as
well (but restricts to one liners) • C++ 11 is even adding them to C++! lambda x, y: x * y # <function <lambda> at 0x10acce938> multiply = lambda x, y: x * y multiply(5, 2) # 10 [](int x, int y) { return x * y; } -
Tricks with Functions • Let’s look at some tricks used
with functions when we have access to them as a proper value -
Tricks with Functions • Let’s look at some tricks used
with functions when we have access to them as a proper value • Higher Order Functions -
Tricks with Functions • Let’s look at some tricks used
with functions when we have access to them as a proper value • Higher Order Functions • Partial Application -
Tricks with Functions • Let’s look at some tricks used
with functions when we have access to them as a proper value • Higher Order Functions • Partial Application • Multiple Argument Lists -
Tricks with Functions • Let’s look at some tricks used
with functions when we have access to them as a proper value • Higher Order Functions • Partial Application • Multiple Argument Lists • Currying -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming • The idea is to truly take advantage of functions as values -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming • The idea is to truly take advantage of functions as values • A Higher Order Function either ... -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming • The idea is to truly take advantage of functions as values • A Higher Order Function either ... • Accepts one or more functions as “input” -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming • The idea is to truly take advantage of functions as values • A Higher Order Function either ... • Accepts one or more functions as “input” • Produces a function as its result (“output”) -
Higher Order Functions • Higher Order functions are one of
the most leveraged patterns in functional programming • The idea is to truly take advantage of functions as values • A Higher Order Function either ... • Accepts one or more functions as “input” • Produces a function as its result (“output”) • Or, technically... both! -
Higher Order Functions def math(x: Int, y: Int, op: (Int,
Int) => Int) = { op(x, y) } val multiply = (x: Int, y: Int) => { x * y } val add = (x: Int, y: Int) => { x + y } val sub = (x: Int, y: Int) => { x - y } val divide = (x: Int, y: Int) => { x / y } println(math(10, 5, divide)) // 2 println(math(10, 5, multiply)) // 50 println(math(10, 5, add)) // 15 println(math(10, 5, sub)) // 5 -
Patterns around Higher Order Functions • There are any number
of patterns we can leverage Higher Order Functions in... -
Patterns around Higher Order Functions • There are any number
of patterns we can leverage Higher Order Functions in... • Let’s talk about 2 -
Patterns around Higher Order Functions • There are any number
of patterns we can leverage Higher Order Functions in... • Let’s talk about 2 • “Execute Around” / “Loan” Patterns -
Patterns around Higher Order Functions • There are any number
of patterns we can leverage Higher Order Functions in... • Let’s talk about 2 • “Execute Around” / “Loan” Patterns • Inline Manipulation (“map”, “flatMap”, “filter”, etc) -
Executing Around / Loaning a Resource val file = scala.io.Source("anon.scala")
for (line <- file) { println(line) } // ... we forgot to close the file -
Executing Around / Loaning a Resource def iterateFile(file: String, op:
Iterator[String] => Unit) = { val fh = scala.io.Source.fromFile(file) op(fh.getLines) // CLOSE IT! fh.close() } iterateFile("anon.scala", { file => for (line <- file) println(file) }) -
Why “Execute Around”? • Enforces encapsulation and value “leakage”/”exposure” •
User gets limited (as in you control the view of the resource) access to some resource (often IO based) • Much easier to handle cleanup, restrict access to certain values/params and “hide implementation” -
Manipulating Data ... Inline! val fh = scala.io.Source.fromFile("anon.scala") fh.getLines.foreach( line
=> println(line) ) // Even simpler... implicit... fh.getLines.foreach(println) // Filter out blank lines val isBlank = (x: String) => x == "" val noBlank = fh.getLines.filterNot(isBlank) val blankOnly = fh.getLines.filter(isBlank) // Manipulate on the fly, producing a new datasource val commented = fh.getLines.map{ l => "//%s".format(l) } -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” • Limits access to the “core resource” -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” • Limits access to the “core resource” • More importantly, allows us to more safely control two incredibly important concepts: -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” • Limits access to the “core resource” • More importantly, allows us to more safely control two incredibly important concepts: • State -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” • Limits access to the “core resource” • More importantly, allows us to more safely control two incredibly important concepts: • State • Mutability -
Why Manipulate Inline? • Similar reasons to “Execute Around” come
into play... • Enforces encapsulation and value “leakage”/”exposure” • Limits access to the “core resource” • More importantly, allows us to more safely control two incredibly important concepts: • State • Mutability • ... which we’ll elaborate on shortly. -
Partially Applied Functions • Taking advantage of this “reusable, composable
value” concept ... • We can fill in some of the required arguments to a function, and then hand a “partially applied” view to someone else to finish -
Partially Applied Functions def multiply(x: Int, y: Int) = {
x * y } // multiply: (x: Int, y: Int)Int /* multiply(50, 1) Int = 50 */ def squared = multiply(_: Int, 2) // squared: Int => Int /* squared(50) Int = 100 */ def cubed = multiply(_: Int, 3) /* cubed(50) Int = 150 */ -
Accepting Multiple Arguments • Sometimes, there’s some composable beauty in
taking multiple argument lists instead of one • Many functional languages allow this (as well as tricks around them) • Think about how we can clean up our multiply function based on the tricks we just pulled with partial application -
Accepting Multiple Arguments def multiply(multiplier: Int)(value: Int) = { value
* multiplier } // multiply: (multiplier: Int)(value: Int)Int /* multiply(1)(50) Int = 50 */ -
Currying Favor • With “Currying” we can leverage multiple argument
lists (technically, to “curry” they must each take a single argument) partially applied • This gives us a chain of callable functions • With partial application, we can “lazily” evaluate this chain -
Currying Favor def squared = multiply(2) _ // squared: Int
=> Int /* squared(50) Int = 100 */ def cubed = multiply(3) _ // cubed: Int => Int /* cubed(50) Int = 150 */ -
Higher Order Functions + Multiple Args • What I think
of as the “beauty” of currying can also be used to clean up things like a “loan” method which takes initialization params • Separate out our function arg from our non-function args ... -
Higher Order Functions + Multiple Args def math(x: Int, y:
Int)(op: (Int, Int) => Int) = { op(x, y) } val multiply = math(10, 5) { (x, y) => x * y } val add = math(10, 5) { (x, y) => x + y } val sub = math(10, 5) { (x, y) => x - y } val divide = math(10, 5) { (x, y) => x / y } println(divide) // 2 println(multiply) // 50 println(add) // 15 println(sub) // 5 -
Higher Order Functions + Multiple Args def iterateFile(file: String)(op: Iterator[String]
=> Unit) = { val fh = scala.io.Source.fromFile(file) op(fh.getLines) // CLOSE IT! fh.close() } iterateFile("anon.scala") { file => for (line <- file) println(file) }