Functional Programming
Contact me: hadoope@gmail.com
Let’s Rock!
Why FP ???
Single Threading can’t scale,
but multi-ple threading is hard!
Simple is Beautiful!
Beautiful Concurrency ???
Thread Safe
Synchronized
Deadlock
Livelock
Races
Debugging
Mutable shared state!!!
Functional Programming
No Mutable
In computer science, functional programming is a programming paradigm,
a style of building the structure and elements of computer programs,
that treats computation as the evaluation of mathematical functions and
avoids state and mutable data.
First Class Function
Higher-Order Function
Purify
Curry
Lazy Evaluation
Monoid
Monad
Tail Recursive
First Class Function
http://jsfiddle.net/hadoope/RAYy7/
Number Versus Function
Higher-Order Function
Functions that take other functions
Functions that return other functions
var people = [{name: "Fred", age: 65}, {name: "Lucy", age: 36}];
_.max(people, function(p) { return p.age });
function always(VALUE) {
return function() {
return VALUE;
};
};
Currying
Currying using Lambda calculus
(x, y) -> x * x + y *y
x -> y -> x * x + y *y
=
Currying in JavaScript
function curry3(fun) {
return function(last) {
return function(middle) {
return function(first) {
return fun(first, middle, last);
};
};
};
};
function no_curry(fun, last, middle, first){
return fun(last, middle, first);
}
Define a Method
Define a Method in
Currying Way
Recursion and Tail Recursive
def factorial(n)
if (n == 1)
return 1
else
return n* factorial(n-1)
end
end
@tailrec def factorial(acc: Int, n:Int ) = {
if (n <= 1) acc
else factorial( n * acc, n - 1)
}
Lazy Evaluation
In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy
which delays the evaluation of an expression until its value is needed (non-strict evaluation)
and which also avoids repeated evaluations (sharing).
Lazy Evaluation
 Performance increases by avoiding needless calculations, and error conditions in
evaluating compound expressions
 The ability to construct potentially infinite data structures.
 The ability to define control flow (structures) as abstractions instead of primitives
Pattern Matching
• Object Matching
Import scala.util.Random
var randomInt = new Random().nextInt(10)
randomInt match {
case 7 => println(“lucky seven”)
case otherNumber => println( “get” + otherNumber)
}
Pattern Matching
• Type Matching
var items = List(1, “foo”, 3.5)
for (item <- items) {
item match {
case i: Int => println(“got an Integer: ” + i)
case s: String => println(“got a String: ” + s)
case d: Double => println(“got a double: ” + d)
case other => println(“got others” + other)
}
}
Pattern Matching
Functionalpolymorphism
Versus
OOpolymorphism
Monoid
Just what is a monoid, then? It is simply an implementation of an interface
governed by some laws. Stated tersely, a monoid is a type together with an
associative binary operation (op) which has an identity element (zero).
trait Monoid[A] {
def op(a1: A, a2: A): A
def zero: A
}
def listMonoid[A] = new Monoid[List[A]] {
def op(a1: List[A], a2: List[A]) = a1 ++ a2
def zero = Nil
}
Monoid will buy us ???
Associativity brings high parallelism
op(a, op(b, op(c,d)))Folding to the right:
After folding in parallel: op( op(a,b), op(c,d))
op(op(op(a, b), c), d)Folding to the right:
Monad
In functional programming, a monad is a structure that
represents computations defined as sequences of steps. A type with a monad
structure defines what it means to
chain operations, or nest functions of that type together. This allows the programmer
to build pipelines that process data in steps, in which each action is decorated with
additional processing rules provided by the monad.
Functional Javascript
• Collection-Centric Programming
Functional Javascript
• Collection-Centric Programming (map, reduce
and filter)
http://jsfiddle.net/hadoope/xhQ4P/
Monad using Javascript
var stack = [];
stack.push(4);
stack.push(5);
stack.pop(); // 5
stack.pop(); // 4
Normal Style
http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html
Monad using Javascript
http://jsfiddle.net/hadoope/FcD5S/
Continuation-Passing Style
Monad using Javascript
• Currying push and pop
http://jsfiddle.net/hadoope/62bfe/2/
Monad using Javascript
• Preparing bind to Handle Intermediate Stacks
http://jsfiddle.net/hadoope/Lsgw5/
Monad Using Haskell
computation = push 4 >>= _ ->
push 5 >>= _ ->
pop >> a ->
pop >>= b->
return $ (show a) ++ “ : ” ++ (show b)
Computation = do push 4
push 5
a <- pop
b <- pop
return $ (show a) ++ “ : “ ++ (show b)
https://www.coursera.org/course/progfun
Thank You
29

Functional Programming

  • 1.
    Functional Programming Contact me:hadoope@gmail.com Let’s Rock!
  • 2.
    Why FP ??? SingleThreading can’t scale, but multi-ple threading is hard! Simple is Beautiful!
  • 3.
    Beautiful Concurrency ??? ThreadSafe Synchronized Deadlock Livelock Races Debugging Mutable shared state!!!
  • 4.
  • 5.
    In computer science,functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data.
  • 6.
    First Class Function Higher-OrderFunction Purify Curry Lazy Evaluation Monoid Monad Tail Recursive
  • 7.
  • 8.
    Higher-Order Function Functions thattake other functions Functions that return other functions var people = [{name: "Fred", age: 65}, {name: "Lucy", age: 36}]; _.max(people, function(p) { return p.age }); function always(VALUE) { return function() { return VALUE; }; };
  • 9.
  • 10.
    Currying using Lambdacalculus (x, y) -> x * x + y *y x -> y -> x * x + y *y =
  • 11.
    Currying in JavaScript functioncurry3(fun) { return function(last) { return function(middle) { return function(first) { return fun(first, middle, last); }; }; }; }; function no_curry(fun, last, middle, first){ return fun(last, middle, first); } Define a Method Define a Method in Currying Way
  • 12.
    Recursion and TailRecursive def factorial(n) if (n == 1) return 1 else return n* factorial(n-1) end end @tailrec def factorial(acc: Int, n:Int ) = { if (n <= 1) acc else factorial( n * acc, n - 1) }
  • 13.
    Lazy Evaluation In programminglanguage theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
  • 14.
    Lazy Evaluation  Performanceincreases by avoiding needless calculations, and error conditions in evaluating compound expressions  The ability to construct potentially infinite data structures.  The ability to define control flow (structures) as abstractions instead of primitives
  • 15.
    Pattern Matching • ObjectMatching Import scala.util.Random var randomInt = new Random().nextInt(10) randomInt match { case 7 => println(“lucky seven”) case otherNumber => println( “get” + otherNumber) }
  • 16.
    Pattern Matching • TypeMatching var items = List(1, “foo”, 3.5) for (item <- items) { item match { case i: Int => println(“got an Integer: ” + i) case s: String => println(“got a String: ” + s) case d: Double => println(“got a double: ” + d) case other => println(“got others” + other) } }
  • 17.
  • 18.
    Monoid Just what isa monoid, then? It is simply an implementation of an interface governed by some laws. Stated tersely, a monoid is a type together with an associative binary operation (op) which has an identity element (zero). trait Monoid[A] { def op(a1: A, a2: A): A def zero: A } def listMonoid[A] = new Monoid[List[A]] { def op(a1: List[A], a2: List[A]) = a1 ++ a2 def zero = Nil }
  • 19.
    Monoid will buyus ??? Associativity brings high parallelism op(a, op(b, op(c,d)))Folding to the right: After folding in parallel: op( op(a,b), op(c,d)) op(op(op(a, b), c), d)Folding to the right:
  • 20.
    Monad In functional programming,a monad is a structure that represents computations defined as sequences of steps. A type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad.
  • 21.
  • 22.
    Functional Javascript • Collection-CentricProgramming (map, reduce and filter) http://jsfiddle.net/hadoope/xhQ4P/
  • 23.
    Monad using Javascript varstack = []; stack.push(4); stack.push(5); stack.pop(); // 5 stack.pop(); // 4 Normal Style http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html
  • 24.
  • 25.
    Monad using Javascript •Currying push and pop http://jsfiddle.net/hadoope/62bfe/2/
  • 26.
    Monad using Javascript •Preparing bind to Handle Intermediate Stacks http://jsfiddle.net/hadoope/Lsgw5/
  • 27.
    Monad Using Haskell computation= push 4 >>= _ -> push 5 >>= _ -> pop >> a -> pop >>= b-> return $ (show a) ++ “ : ” ++ (show b) Computation = do push 4 push 5 a <- pop b <- pop return $ (show a) ++ “ : “ ++ (show b)
  • 28.
  • 29.