Date post: | 13-Apr-2017 |
Category: |
Science |
Upload: | aaron-levin |
View: | 63 times |
Download: | 2 times |
When Life Gives you Functions
Make Functional Programs!aaron levin07.09.2016
Thank you Ellen, Duana, and Open Tech School!
Outline
1. Who is Aaron Levin?
2. What is Functional Programming?
3. How Functional Programming Can Benefit You
4.🎉🎉🎉🎉
Who is Aaron Levin
MSc Pure Mathematics
Started Programming at age 30 👴
Building Recommender Systems at SoundCloud
But also have worked as:Taco Conjurer @ TacoTime 🌮Telemarketer @ The WeedMan 🌿Rare Record Dealer @ eBay ⏺Music Director @ Community Radio Station 📻
Who is Aaron Levin (really)
First programming job in Scala.
Was once paid actual Real World™ money to write Haskell
Wrote authentication framework for http library servant.
Author of a few Haskell libraries:- free-vl- haskell-kubernetes
What is Functional Programming?
Wait, what is a function?
What is a function?
Maths: a function maps input to output.
f : R -> Rf(x) = x * x
Programming: a function receives input, performs actions, returns output.
int main( int argc, const char* argv[] ) {printf( "\nHello World\n\n" );
}
OO Programming: a function is a method on an object
class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. }}
How can we program with functions?
Functional Programming LanguagesFunctional Languages
LISP
Clojure
Erlang
Haskell
OCaml
SML
Languages with Functional Features
Javascript
Ruby
Python
Java (8)
C++Who can know what to make of this one?
With so many functional languages, what makes a language functional?
Let’s ask celebrity programmers!“You are programming with functions? Then you are doing functional programming. And your language is a functional programming language.”- @raganwald
“A programming paradigm, a coding style, a mindset, a sexy, buzz-wordy trend”- @AnjanaVakil
“Functional programming is a style of programming which models computations as the evaluation of expressions.”- Haskell.org
Let’s Ask (more) Celebrity Programmers
“Functional programming is about writing pure functions, about removing hidden inputs and outputs as far as we can, so that [our code just describes] a relationship between inputs and outputs.”- @krisajenkins
“What if instead of telling the computer what to do, we told the computer what things are.”- @_K_E_L_S_E_Y
“2+2 is functional programming [...] the proper OO way is:x = new int(2); x.add(2); return x;”- @chris__martin
To make matters worse...
Things Associated With Functional Programming
Higher-Order Functions
Immutability
Purity
Pattern Matching
Lazy Evaluation
Recursion
Type Inference
Algebraic Data Types
...
Take a step backbreatheLet’s start over
What is Functional Programming?
There are lots of things to program with:
objects, statements, relations, instructions, messages
There are lots of things to program with:
functions!
Functional Programming Is
1. Programming with Functions that are Higher-Order
2. Programming with Data that is Immutable
3. Designing Systems that minimize the location of Side-Effects
Programming with Higher-Order Functions
A Higher-Order Function may take another function as an argument.
Allows you to pass functions to functions!
Most prevalent example: call-backs.
Programming with Higher-Order Functions
Traditional
var nums = [1, 2, 3];var result = [];
for(num in nums) { result.push(num * 10);}
Functional
var nums = [1, 2, 3];
var result = nums.map(function(num) { return num * 10; });
[1, 2, 3] ---> [10, 20, 30]
Programming with Higher-Order Functions
Benefits:
1. No indexing / out-of-bounds issues
2. Don’t care about array structure
3. Don’t care about how to iterate through structure
4. Could work for anything that can be traversed! Trees, etc.
Programming with Immutable Data
Immutable data cannot be changed after it is created.
Cannot score++ with an immutable score!
Programming with Immutable Datadef collision_points(self, other): if self.collide(other) and other.is_coin: state.high_score++ elif self.collide(other): state.high_score = 0
def collision_points(self, other, state): new_state = copy(state) if self.collide(other) and other.is_coin: new_state.high_score++ elif self.collide(other): new_state.high_score = 0 return new_state
Programming with Immutable Datadef collision_points(self, other): if self.collide(other) and other.is_coin: state.high_score = state.high_score + 1 elif self.collide(other): state.high_score = 0
def collision_points(self, other): if self.collide(other) and other.is_coin: return {‘mutate’: ‘increment’, ‘amount’: 1} elif self.collide(other): return {‘mutate’: ‘reset’, ‘amount’: 0} else: return None
return facts!
a description of how to change the world!
Programming with Immutable Data
Benefits
1. Know exactly where and how state is modified
2. Easier to test
3. Can share data with concurrent threads / processes safely
4. Easily parallelizable
5. Easily persisted to disk
6. Basically everything is 100000000% satisfaction guaranteed better when things are immutable
Minimize Location of Side-Effects
A function is said to have a Side-Effect if it mutates state or has an observable interaction.
public static void main(String[] args) { System.out.println("Hello World!"); // ← Side Effect! }
Pure functions don’t have Side Effects (Referential Transparency)
Handling side-effects is necessary for interacting with the real world!
Minimize Location of Side-Effects
Values
Pure function
Function interfacing with outside world
Minimize Location of Side-Effects
The Outside World™
Manage Program State Open filesConnect to DBReceive HTTP Req.Receive Mouse InputTalk to GPURead stdinOutput to stdoutLaunch programsSend UDP packets
request.body.rewind
request.body
Minimize Location of Side-Effects
Benefits
1. Don’t have to remember things
2. How do I know if someone “already read it”? Don’t have to understand the entire program!
3. Test core algorithms more easily
RecapWhat is Functional Programming?
Functional Programming Is
1. Programming with Functions that are Higher-Order
2. Programming with Data that is Immutable
3. Designing Systems that minimize the location of Side-Effects
Why don’t we always program with functions?
Why Don’t We Always Program With Functions?
Some languages don’t support it (Java <7)
Requires thinking very deeply about program architecture.
Is not always performant
Many APIs are written in a non-FP style (e.g. java’s old Time library)
What are the benefits of Functional Programming?
Benefits of Functional Programming
Safer
Easier to understand your programs
Easier to debug your programs
Easier to test your programs
Make APIs easier to use
Make static typing systems more powerful
It’s fun!
It’s simple!
It’s hard!
What next?
What Next?
1. Try re-writing programs in a more functional style!
2. Learn a functional language! (Haskell or OCaml)
3. How to encode data (numbers, lists, strings) as functions! (Church-encoding)
Thanks!
Ende.