Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Functional Programming

Introduction to Functional Programming

A presentation given at AIC16 (Asynchrony Internal Conference 2016) to introduce functional programming and functional concepts to my coworkers.

Some illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html

Websites Referenced:

Functional Programming vs. Imperative Programming (C#) (https://msdn.microsoft.com/en-us/library/mt693186.aspx)

Recursion, Tail Calls and Trampolines (http://www.datchley.name/recursion-tail-calls-and-trampolines/)

Lean You Haskell for Great Good (http://learnyouahaskell.com)

Swift Functors, Applicatives, and Monads in Pictures, (http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/)

Kartik Patel

July 15, 2016
Tweet

More Decks by Kartik Patel

Other Decks in Programming

Transcript

  1. Table of Content 1 - Terms 2 - Functions 3

    - Recursion 4 - Tail-Call Recursion 5 - Higher Order Functions 6 - Trampolines 7 - Currying 8 - Types & Typeclasses 9 - Optionals 10 - Functors 11 - Applicatives
  2. Terms Imperative Programming Imperative Programming Imperative programming is a programming

    paradigm that uses statements that change a program's state. An imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates. https://en.wikipedia.org/wiki/Imperative_programming
  3. Terms Functional Programming Functional Programming Functional programming is a programming

    paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. Programming is done with declarations instead of statements. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming. https://en.wikipedia.org/wiki/Functional_programming
  4. Terms Imperative vs Declarative Imperative Version public List<Foo> FindFoos(int minSize)

    { List<Foo> result = new ArrayList<Foo>(); for (Foo foo: foos) { if (foo.size >= minSize) { result.add(foo); } } return result; } Declarative Version foos.filter(_.size >= minSize)
  5. Terms Imperative vs Functional Programming Characteristic Imperative Functional Programmer Focus

    How to perform tasks and how to track changes in state What information is desired and what transformations are required State Changes Important Non-existent Order of Execution Important Low importance Primary Flow Control Loops, conditionals, and method calls Function calls, including recursion Primary Manipulation Unit Instances of structures or classes Functions as first-class objects and data collections https://msdn.microsoft.com/en-us/library/mt693186.aspx
  6. Terms Side Effects No Side Effects It doesn’t rely on

    data outside the current function, and it doesn’t change data that exists outside the current function.
  7. Terms Immutable Data Immutable Data Variables in functional languages are

    replaced by symbols or values that cannot be changed. After assigning a value such as number or a string to a symbol (for example, num), the value referred to by the symbol cannot be changed. Data structures that are used in functional programs are also immutable. Once an object is created (e.g., to represent a character or item in a game) it cannot be changed. To update the game state, the program needs to create a new object representing the changed state.
  8. Functions Definition Functions Expressions that are applied to an argument

    or input, and once applied, can be reduced or evaluated
  9. Functions Mathematics f(x) = x f(1) = 1 f(2) =

    2 g(x) = x + 1 g(1) = 1 + 1 = 2 g(2) = 2 + 1 = 3 g(f(x)) = f(x) + 1 g(f(x)) = x + 1 g(g(x)) = g(x) + 1 g(g(x)) = x + 1 + 1
  10. Recursion Definition Recursion Means of computing results that may require

    an indefinite amount of work to obtain through the use of repeated function application Base Case Input(s) for which the function produces a result trivially (without recurring) Recursive Step Input(s) for which the program recurs (calls itself)
  11. Recursion Example Imperative Version func maximum_imperative(arr: [Int]) -> Int {

    var max: Int = 0 for num in arr { max = num < max ? max : num } return max }
  12. Recursion Example Recursive Version func max(a: Int, _ b: Int)

    -> Int { return a < b ? b : a } func maximum_recursive(arr: [Int]) -> Int { if arr.count == 1 { return arr.first! } else { let head = arr.first! let tail = Array(arr.dropFirst()) return max(head, maximum_recursive(tail)) } }
  13. Recursion Call Stack Call Stack maximum([1,2]) maximum([1,2,3]) maximum([1,2,3]) maximum([1,2,3,4]) maximum([1,2,3,4])

    maximum([1,2,3,4]) maximum([1,2,3,4,5]) maximum([1,2,3,4,5]) maximum([1,2,3,4,5]) maximum([1,2,3,4,5])
  14. Tail-Call Recursion Example Tail-Call Recursive Version func max(a: Int, _

    b: Int) -> Int { return a < b ? b : a } func maximumTailCallRecursive(arr: [Int], _ currentMax: Int = 0) -> Int { if arr.count == 0 { return currentMax } else { let head = arr.first! let tail = Array(arr.dropFirst()) return maximumTailCallRecursive(tail, max(head, currentMax)) } }
  15. Higher Order Functions Definition Higher Order Function take functions as

    parameters and return functions as return values g(f(x)) = f(x) + 1 g(f(x)) = x + 1 g(g(x)) = g(x) + 1 g(g(x)) = x + 1 + 1 h(x) = i(y) z = j(x, y)
  16. Higher Order Functions Common Examples Map Map takes a function

    and a collection of items. It produces a new collection by applying the function to every element in the collection Reduce Reduce takes a function and a collection of items. It returns a value that is created by combining the items. func maximumHOF(arr: [Int]) -> Int { return arr.reduce(0, combine: max) } func increaseAllByOne(arr: [Int]) -> [Int] { return arr.map({ $0 + 1 }) }
  17. Trampolines Example Trampoline Version function trampoline(fn){ return function(){ var res

    = fn.apply(this, arguments); while(res instanceof Function){ res = res(); } return res; } } function maximumTrampoline(arr, res) { res = Math.max(res, arr[0]) || arr[0]; return arr.length == 1 ? res : function() { return maximumTrampoline(arr.slice(1), res); }; } trampoline(maximumTrampoline)([1,2,3,4,5])
  18. Trampolines Call Stack Call Stack res([2,3,4,5], 1) res([3,4,5], 2) trampoline

    (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5]) res([4,5], 3) res([5], 4) trampoline (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5]) trampoline (maximumTrampoline) ([1,2,3,4,5])
  19. Currying Definition & Example Currying A curried function is a

    function that, instead of taking several parameters, always takes exactly one parameter. Then when it's called with that parameter, it returns a function that takes the next parameter, and so on. func max(a: Int) -> (Int-> Int) { return { b in a < b ? b : a } } let m5 = max(5) m5(10) m5(1)
  20. Types & Typeclasses Definition Type A type is a kind

    of label that every expression has. It tells us in which category of things that expression fits. The expression True is a boolean, "hello" is a string, etc. Typeclass A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. A lot of people coming from OOP get confused by typeclasses because they think they are like classes in object oriented languages. Well, they're not. You can think of them kind of as Java interfaces, only better.
  21. Types & Typeclasses Examples Type 5 :: Integer 'a' ::

    Char inc :: Integer -> Integer [1,2,3] :: [Integer] ('b',4) :: (Char,Integer) Typeclass show :: (Show a) => a -> String read :: (Read a) => String -> a
  22. Optionals Definition Here’s a simple value: And we know how

    to apply a function to this value: Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  23. Optionals Definition Optionals A type that can either have nothing

    or just a single value Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  24. Functors Why When a value is wrapped in a context,

    you can’t apply a normal function to it: This is where map (fmap in Haskell) comes in: Optional.Some(2).map({$0 + 3}) Optional.Some(2) + 3 Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  25. Functors Definition A Functor is any type that defines how

    map applies to it. Here’s what happening behind the scenes: Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  26. Functors Arrays What happens when you apply a function to

    an array? Arrays are functors too! Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  27. Applicatives Why Applicative’s take it to the next level. With

    an applicative, our values are wrapped in a context just like Functors: But out functions are wrapped in a context too! Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  28. Applicative's Definition <*> knows how to apply a function wrapped

    in a context tp a value wrapped in a context Illustrations by Aditya Bhargava, http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
  29. Resources Functional Programming vs. Imperative Programming (C#) https://msdn.microsoft.com/en-us/library/mt693186.aspx Recursion, Tail

    Calls and Trampolines http://www.datchley.name/recursion-tail-calls-and-trampolines/ Lean You Haskell for Great Good http://learnyouahaskell.com Swift Functors, Applicatives, and Monads in Pictures http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/