• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Why we cannot ignore Functional Programming
 

Why we cannot ignore Functional Programming

on

  • 3,282 views

 

Statistics

Views

Total Views
3,282
Views on SlideShare
3,182
Embed Views
100

Actions

Likes
7
Downloads
31
Comments
0

5 Embeds 100

https://twitter.com 80
http://127.0.0.1 13
http://www.linkedin.com 4
http://twitter.com 2
http://tweetedtimes.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Why we cannot ignore Functional Programming Why we cannot ignore Functional Programming Presentation Transcript

    • by Massimiliano Dessìdesmax74@yahoo.comtwitter: @desmax74and Mario Fuscomario.fusco@gmail.comtwitter: @mariofusco
    • Moores lawNow achievedby increasing the number of cores The number of transistors on integrated circuits doubles approximately every two years
    • Moores lawNow achievedby increasing the number of cores The number of transistors on integrated circuits doubles approximately every two years
    • Amdahls lawThe speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program
    • Concurrency & ParallelismConcurrent programmingManaging concurrent requests Parallel programming Running multiple tasks at the same time Both are too hard!
    • The cause of the problem … Mutable state + Parallel processing = Non-determinism
    • The cause of the problem … Mutable state + Parallel processing = Non-determinism Functional Programming
    • … and its effectsRace conditions Starvation Deadlocks Livelocks
    • … and its effectsRace conditions Starvation Deadlocks Livelocks Too hard to think about them!
    • The native Java concurrency model Based on: Threads Semaphores Locks SynchronizationThey are sometimes plain evil … … and sometimes a necessary pain … … but always the wrong default
    • Different concurrency modelsShared mutable state (threads + locks) Isolated mutable state (actors) Purely immutable (pure functions)
    • Summing attendants ages (Threads)class Blackboard { int sum = 0; int read() { return sum; } void write(int value) { sum = value; }} class Attendant implements Runnable { int age; Blackboard blackboard; public void run() { synchronized(blackboard) { int oldSum = blackboard.read(); int newSum = oldSum + age; blackboard.write(newSum); } } }
    • Summing attendants ages (Actors)class Blackboard extends UntypedActors { int sum = 0; public void onReceive(Object message) { if (message instanceof Integer) { sum += (Integer)message; } }} class Attendant { int age; Blackboard blackboard; public void sendAge() { blackboard.sendOneWay(age); } }
    • Summing attendants ages (Functional)class Blackboard { final int sum; Blackboard(int sum) { this.sum = sum; }}class Attendant { int age; Attendant next; public Blackboard addMyAge(Blackboard blackboard) { final Blackboard b = new Blackboard(blackboard.sum + age); return next == null ? b : next.myAge(b); }}attendants.foldLeft(new Blackboard(0), (att, b) -> new Blackboard(b.sum + att.age));
    • What is a functional program?A program created using only pure functionsNo side effects allowed like: Reassigning a variable Modifying a data structure in place Setting a field on an object } Throwing an exception or halting with an error } Printing to the console Reading user input Reading from or writing to a file Drawing on the screenFunctional programming is a restriction on how we write programs, but not on what they can do
    • The OOP/FP dualismclass Bird OOP vs. …class Cat { def capture(b: Bird): Unit = ... def eat(): Unit = ...}val cat = new Catval bird = new Birdcat.capture(bird)cat.eat() class Cat class Bird trait Catch … FP The story trait FullStomach def capture(prey: Bird, hunter: Cat): Cat with Catch def eat(consumer: Cat with Catch): Cat with FullStomach val story = (capture _) andThen (eat _) story(new Bird, new Cat)
    • What is a (pure) function?A function with input type A and output type Bis a computation which relates every value a of type A to exactly one value b of type B such that b is determined solely by the value of a But, if it really is a function, it will do nothing else
    • Referential transparencyAn expression e is referentially transparent if for all programs p, all occurrences of e in p can be replaced by the result of evaluating e, without affecting the observable behavior of p A function f is pure if the expression f(x) is referentially transparent for all referentially transparent x
    • RTString x = "purple";String r1 = x.replace(p, t);String r2 = x.replace(p, t); vs.String r1 = "purple".replace(p, t); r1: "turtle"String r2 = "purple".replace(p, t); r2: "turtle" Non-RTImmutable StringBuilder x = new StringBuilder("Hi"); StringBuilder y = x.append(", mom"); String r1 = y.toString(); Mutable String r2 = y.toString(); String r1 = x.append(", mom").toString(); Expression not r1: "Hi, mom"replaceable with String r2 = x.append(", mom").toString(); r1: "Hi, mom, mom" its result
    • RT winsUnder a developer point of view: Easier to reason about since effects of evaluation are purely local Use of the substitution model: its possible to replace a term with an equivalent oneUnder a performance point of view: The JVM is free to optimize the code by safely reordering the instructions No need to synchronize access to shared data
    • ImmutabilityImmutable objects can be shared amongmany threads exactly because none ofthem can modify itIn the same way immutable (persistent)data structures can be shared without anyneed to synchronize the different threadsaccessing them
    • Persistent Collections 5 3 8 E 4 7 9 E E E E E E
    • Persistent Collections 52 3 8 E 4 7 9 E E E E E E
    • Persistent Collections 5 3 5 2 3 8E E E 4 7 9 E E E E E E
    • Persistent Collections 5 New Root 3 Old Root 5 2 3 8 Shared dataE E E 4 7 9 E E E E E E
    • Modularityclass Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!");} } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); }
    • Modularityclass Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!");} } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logicpublic Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2;}public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2));}
    • Modularityclass Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!");} } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logicpublic Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2;}public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2));} declareWinner(players.reduceLeft(maxScore)) reuse maxScore to compute the winner among a list of players
    • Modularityclass Player { String name; public void declareWinner(Player p) { int score; System.out.println(p.name + " wins!");} } public void winner(Player p1, Player p2) { if (p1.score > p2.score) declareWinner(p1) else declareWinner(p2); } Separate computational logicpublic Player maxScore(Player p1, Player p2) { from side effects return p1.score > p2.score ? p1 : p2;}public void winner(Player p1, Player p2) { declareWinner(maxScore(p1, p2));}declareWinner(players.parallel().reduceLeft(maxScore)) Its trivial to parallelize "internal" iteration
    • A pure functional core functional coreAny function with side-effects can be split into a pure function at thecore and a pair of functions with side-effect. This transformation canbe repeated to push side-effects to the outer layers of the program.