Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young 2012-05.

Similar presentations


Presentation on theme: "Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young 2012-05."— Presentation transcript:

1 Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young 2012-05

2 Agenda Definition Definition Popular FP languages Popular FP languages First-class functions First-class functions lambda expressions lambda expressions Higher-order functions Higher-order functions Closures Closures Currying Currying Common collection operations Common collection operations Immutability Immutability Recursion Recursion Lazy evaluation Lazy evaluation

3 Definition In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. (Wikipedia) In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. (Wikipedia) In functional programming, programs are executed by evaluating expressions, in contrast with imperative programming where programs are composed of statements which change global state when executed. Functional programming typically avoids using mutable state. (Haskell Wiki) In functional programming, programs are executed by evaluating expressions, in contrast with imperative programming where programs are composed of statements which change global state when executed. Functional programming typically avoids using mutable state. (Haskell Wiki) Broadly speaking, functional programming is a style of programming in which the primary method of computation is the application of functions to arguments. (University of Nottingham) Broadly speaking, functional programming is a style of programming in which the primary method of computation is the application of functions to arguments. (University of Nottingham)

4 Popular FP Languages Pure Functional: Pure Functional: LISP LISP Scheme, Common LISP, Clojure Scheme, Common LISP, Clojure Haskell Haskell Erlang Erlang O’Caml (ML) O’Caml (ML) F# F# OO-FP OO-FP Ruby Ruby Scala Scala C# C# ? JavaScript JavaScript All have a garbage collector All have a garbage collector

5 First-class Functions Definition Definition Can be stored as data structures do Can be stored as data structures do Can be passed to other functions Can be passed to other functions Can be returned from other functions Can be returned from other functions What’s the deal? What’s the deal? We can model computations We can model computations

6 Lambda Expressions Theory originated from Lambda Calculus. http://www.utdallas.edu/~gupta/courses/apl/lambda. pdf Theory originated from Lambda Calculus. http://www.utdallas.edu/~gupta/courses/apl/lambda. pdf http://www.utdallas.edu/~gupta/courses/apl/lambda. pdf http://www.utdallas.edu/~gupta/courses/apl/lambda. pdf Anonymous functions that can be assigned to variables Anonymous functions that can be assigned to variables Can be applied Can be applied Free and bound variables (closures) Free and bound variables (closures) Lexical and runtime scope Lexical and runtime scope Functions with multiple arguments (curry) Functions with multiple arguments (curry) Can be composed/nested (higher-order functions) Can be composed/nested (higher-order functions)

7 Lambda in C# SetupRibbonItem(homeRibbionGroup, "Home_ViewNew_ViewIssuer", "Home_ViewNew_ViewIssuer", homeRibbionResourceManager, homeRibbionResourceManager, Icons.ViewIssuer_16, Icons.ViewIssuer_16, Icons.ViewIssuer_32, Icons.ViewIssuer_32, new List (), new List (), null, null, p => p => { CoreRibbonHelper.OpenIssuerTransitionScreen(); CoreRibbonHelper.OpenIssuerTransitionScreen(); }); });

8 Closures Functions that have free variables bound at some outer scope (lexical closures) Functions that have free variables bound at some outer scope (lexical closures) Characteristics Characteristics Closures establish a new variable scope Closures establish a new variable scope Code within a closure can access the symbols defined outside Code within a closure can access the symbols defined outside

9 JavaScript Pattern Using Closures (function(window) {...... var jQuery = (function() { var jQuery = (function() {...... })(); })();......})(window);

10 Currying A -> B -> C -> D => A -> (B -> (C -> D)) Scala Example Scala Example def add(a: Int)(b: Int) = { a + b a + b} val increment = add(1) _ println(increment(2)) // 3 def addN(n: Int) = { m: Int => add(n)(m) m: Int => add(n)(m)} def incrementV2 = addN(1) println(incrementV2(2))

11 Higher-order Functions (Functors) Functions that take other functions as input or output functions Functions that take other functions as input or output functions Typical usage: collection manipulation Typical usage: collection manipulation Higher-higher-order functions Higher-higher-order functions Higher-higher-higher-…-higher-order-functions Higher-higher-higher-…-higher-order-functions

12 Common Collection Operations take, takeWhile, drop, dropWhile take, takeWhile, drop, dropWhile foreach, map, flatmap foreach, map, flatmap foldLeft, foldRight, reduce foldLeft, foldRight, reduce filter filter partition, sliding/interleave partition, sliding/interleave zip zip

13 Recursion Substitution to loops? Substitution to loops? Tail Call Optimization (TCO) Tail Call Optimization (TCO) Natural to divide-conquer-merge paradigm and self reference definition Natural to divide-conquer-merge paradigm and self reference definition Trampolines Trampolines

14 Quicksort def quicksort[T](lst: List[T]): List[T] = { lst match { lst match { case Nil => Nil case Nil => Nil case pivot :: rst => case pivot :: rst => val (smaller, bigger) = rst.partition(_ <= pivot) val (smaller, bigger) = rst.partition(_ <= pivot) quicksort(smaller) ::: pivot :: quicksort(bigger) quicksort(smaller) ::: pivot :: quicksort(bigger) }}

15 Fibonacci Sequence def fib(a: Int, b: Int): Stream[Int] = { Stream.cons(a, fib(b, a + b)) Stream.cons(a, fib(b, a + b))} println(fib(0, 1).take(10).toList)

16 Trampoline Example in Clojure (declare funa funb) (defn is-even [n] (if (= n 0) (if (= n 0) true true #(is-odd (dec n)))) #(is-odd (dec n)))) (defn is-odd [n] (if (= n 0) (if (= n 0) false false #(is-even (dec n)))) #(is-even (dec n)))) (trampoline is-even 100000)

17 Trampoline Impl. in Clojure (defn trampoline ([f] ([f] (let [ret (f)] (let [ret (f)] (if (fn? ret) (if (fn? ret) (recur ret) (recur ret) ret))) ret))) ([f & args] ([f & args] (trampoline #(apply f args)))) (trampoline #(apply f args))))

18 Trampoline Example in Scala def even2(n: Int): Bounce[Boolean] = { if (n == 0) Done(true) if (n == 0) Done(true) else Call(() => odd2(n - 1)) else Call(() => odd2(n - 1))} def odd2(n: Int): Bounce[Boolean] = { if (n == 0) Done(false) if (n == 0) Done(false) else Call(() => even2(n - 1)) else Call(() => even2(n - 1))}trampoline(even2(9999))

19 Trampoline Impl. in Scala sealed trait Bounce[A] case class Done[A](result: A) extends Bounce[A] case class Call[A](thunk: () => Bounce[A]) extends Bounce[A] def trampoline[A](bounce: Bounce[A]): A = bounce match { case Call(thunk) => trampoline(thunk()) case Call(thunk) => trampoline(thunk()) case Done(x) => x case Done(x) => x}

20 Lazy Evaluation Thunk Thunk A thunk is a parameterless closure created to prevent the evaluation of an expression until forced at a later time A thunk is a parameterless closure created to prevent the evaluation of an expression until forced at a later time def delay[U](thunk: => U) = { () => thunk () => thunk} val hello = delay { println("Hello world") println("Hello world")} println("God said, there shall be light.") hello()

21 Natural Numbers val N = { def buildNatural(from: Int = 1): Stream[Int] = { def buildNatural(from: Int = 1): Stream[Int] = { from #:: buildNatural(from + 1) from #:: buildNatural(from + 1) } buildNatural() buildNatural()}println(N.take(5).toList)

22 Fibonacci Sequence Revisited def fib(a: Int = 0, b: Int = 1): Stream[Int] = { a #:: fib(b, a + b) a #:: fib(b, a + b)} Int lambda Cons cell Cons Cell

23 A Contrived Example val nat = { def genNatural(from: Int = 1): Stream[Int] = { def genNatural(from: Int = 1): Stream[Int] = { from #:: genNatural(from + 1) from #:: genNatural(from + 1) } genNatural() genNatural()} val fib = { def genFib(a: Int, b: Int): Stream[Int] = { def genFib(a: Int, b: Int): Stream[Int] = { a #:: genFib(b, a + b) a #:: genFib(b, a + b) } genFib(0, 1) genFib(0, 1)} println(nat.zip(fib).map { case (a, b) => case (a, b) => a + b a + b }.filter(_ % 2 == 0).take(5).toList)

24 Immutability Referential Transparency Referential Transparency An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program Can you tell the difference between read only variables and immutable objects? Can you tell the difference between read only variables and immutable objects? What if a language doesn’t allow you to make assignments? What if a language doesn’t allow you to make assignments?

25 Pure and Lazy Haskell Haskell All expressions are lazy All expressions are lazy No assignments are allowed No assignments are allowed No side effects are allowed No side effects are allowed  Dynamic instruction reordering To achieve side effects: IO Monad, Writer Monad To achieve side effects: IO Monad, Writer Monad

26 Advanced Topics Monads Monads List/monad comprehension List/monad comprehension Continuation/Continuation Passing Style (CPS) Continuation/Continuation Passing Style (CPS) Actor model Actor model Co-routine Co-routine Reactive model Reactive model

27 What’s in FP for me? Practicing mind gymnastics, preventing Alzheimer’s dementia Practicing mind gymnastics, preventing Alzheimer’s dementia Basic ideas can improve implementation code Basic ideas can improve implementation code Advanced ideas can effect design decisions Advanced ideas can effect design decisions Predicting trend of language evolvement Predicting trend of language evolvement Having more tools when confronting the challenge of parallelism and non-linear computations Having more tools when confronting the challenge of parallelism and non-linear computations Enriching your pattern repository Enriching your pattern repository

28 Choosing Your Favorite Language Low barrier Low barrier Comprehensive libraries & active community Comprehensive libraries & active community Extensible syntax Extensible syntax Strong type? Strong type? Or maybe just C#... Or maybe just C#...

29 Recommended Readings Structure and Interpretation of Computer Programs Structure and Interpretation of Computer Programs Concepts, Techniques and Models of Computer Programming Concepts, Techniques and Models of Computer Programming Programming in Scala, 2nd Edition Programming in Scala, 2nd Edition Monadic Parser Combinators Monadic Parser Combinators Implementing First-Class Polymorphic Delimited Continuations by a Type-Directed Selective CPS-Transform Implementing First-Class Polymorphic Delimited Continuations by a Type-Directed Selective CPS-Transform

30 Q/A

31


Download ppt "Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young 2012-05."

Similar presentations


Ads by Google