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

An introduction to functional programming

Avatar for Anna Goś Anna Goś
November 08, 2013

An introduction to functional programming

This is a presentation I gave at Rotterdam University of Applied Science for first year students of computer science. The goal of this presentation was to introduce the students to functional programming and its principles.

Avatar for Anna Goś

Anna Goś

November 08, 2013

Other Decks in Programming

Transcript

  1. “Functional programming combines the flexibility and power of abstract mathematics

    with the intuitive clarity of abstract mathematics.” http://xkcd.com/1270/
  2. Agenda A bit of history Principles of functional programming Functional

    vs imperative languages Advantages of functional programming Learning functional programming
  3. Functional Programming isn’t new 1930s 1950s 1960s 1970s 1980s 1987

    2007 2003 2005 Alonzo Church develops the lambda calculus John McCarthy develops Lisp Peter Landin develops ISWIM, first pure functional language John Backus develops FP Robin Milner develops ML David Turner develops a number of lazy functional languages Development of Haskell is initiated, a standard pure functional language First release of Scala, designed by Martin Odersky First version of F#, developed by the F# Software Foundation and Microsoft Rich Hickey releases Clojure
  4. Let’s talk about Immutable state Functions as first-class citizens Pure

    functions Higher-order functions Recursion Lambdas & closures
  5. Immutable state What? Values are never modified. Instead altered copies

    are created. Why? Mutable values makes multithreaded programming difficult. Synchronization is required if multiple threads modify the same value. Immutable values remove the need of synchronization as concurrent reading is safe.
  6. Immutable state ! scala> val score = 5 score: Int

    = 5 scala> score + 4 res11: Int = 9 scala> score res12: Int = 5 ! scala> score = score + 4 <console>:8: error: reassignment to val score = score + 4 Immutable ! int score = 5 score = score + 4 score == 9 Mutable is true!
  7. Function as first-class citizen What? Functions are treated as any

    other piece of data. They can be passed as arguments to other functions or be returned as a result of a function. Why? Fosters code modularity and reusability which results in a smaller codebase.
  8. Functions as first-class citizens ! ! val powerFunction = (x:

    Int) => x * x ! def iTakeAFunctionParam(f: Int => String, x: Int) = f(x) ! def iReturnAFunction(x: Int) = (x) => x + 1 ! def someFunction(x: Int) = { def someOtherFunction(x: Int) = x + 10 … ! } Equal rights
  9. Pure functions What? A function that invoked multiple times with

    the same arguments always yields the same result (referential transparency) and has no side effects. Why? Easier to design, test and understand. Allows the compiler to perform optimisations. Improves performance by making lazy evaluation possible.
  10. Pure functions ! ! def calculateTax(taxRate: Double, amount: Double): Double

    = { taxRate / 100 * amount } ! ! def calculateTax(amount: Double): Double = { getTaxRateFromDatabase() / 100 * amount } ! def calculateTax(taxRate: Double, amount: Double): Double = { val rate = taxRate / 100 * amount saveToDatabase(rate) rate } Pure Impure Relies on external state! Has a side effect!
  11. Higher-order functions What? Higher-order functions are functions which take other

    functions as arguments or return them as results. Why? Useful for combining behavior and reducing the amount of repetition in code.
  12. Higher-order functions ! ! scala> def multiplyByTwo(x: Int) = x

    * 2 ! scala> def sum(f: Int => Int, x: Int, y: Int) = f(x) + f(y) scala> sum(multiplyByTwo, 5, 4) res1: Int = 18 ! int multiplyByTwo(int x) { return x * 2 } ! int sum(int x, int y) { return x + y } sum(multiplyByTwo(5), multiplyByTwo(4)) Higher-order function With no higher-order function Sum is a higher-order function!
  13. Lambdas What? A lambda is a function defined without a

    name, also called an anonymous function. Why? Usually used as convenience for one-time functions with a brief definition.
  14. Lambdas ! scala> val list = List(1, 10, 2, 3,

    7, 14, 15, 17, 20, 4) ! scala> list.filter((x) => x > 10) res0: List[Int] = List(14, 15, 17, 20) ! List<Integer> list = ...; List<Integer> result = new ArrayList<Integer>(); for(Integer number : list) { if(number > 10) { result.add(number); } } Functional Imperative This is a lambda!
  15. Closures What? A closure is a function referencing one or

    more variables which were not passed as arguments to the function and are defined in its enclosing scope. Why? Useful for callbacks in event-driven programming.
  16. Closures ! scala> val prefix =“AB” scala> val decorator =

    (name:String) => prefix + name ! scala> decorator("test") res14: String = ABtest Free variables
  17. Recursion What? Recursion is a method in which a function

    calls itself as a subroutine. Why? Recursion is a way of iterating through a collection without using mutable loop counters.
  18. Recursion ! def sum(xs: List[Int]):Int = { if (xs.isEmpty) 0

    else xs.head + sum(xs.tail) } ! int []numbers = {1, 2, 3, 4, 5}; int total = 0; for(int i = 0; i < numbers.length; i++){ total = total + numbers[i]; } Recursion Iteration Sum calls itself!
  19. So what is functional programming? Strict General A programming paradigm

    which emphasises programming with pure functions and immutable data. A programming paradigm which models computations as evaluation of mathematical functions while avoiding mutable state.
  20. Functional vs Imperative Imperative Functional The code consists of a

    sequence of statements altering the state of a program. The code consists of expressions defining the values and the relationships between them.
  21. Advantages of functional programming Easy to test and understand Modular

    and highly reusable Advantageous in concurrent programming Less and more concise code
  22. Learning functional programming Follow Haskell tutorial online: http://learnyouahaskell.com/ Download Scala

    or Clojure and start having fun in the REPL Google Erik Meijer’s Functional Programming Fundamentals lectures Enroll for Functional Programming Principles in Scala on Coursera