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

Introduction to Functional Programming with Swift

Introduction to Functional Programming with Swift

Hiroshi Kori

April 22, 2016
Tweet

Other Decks in Programming

Transcript

  1. Concept of Functional Programming • Pure functions (Referential Transparency) •

    Immutability • First-class and higher-order functions • Recursion • Strict vs non-strict (lazy) evaluation • Type systems Functional Programming Imperative Programming
  2. Pure functions (Referential Transparency) • No side effect! (No dependency

    on mutable states) • Same result for the same arguments • Testability • Easier to expect result • More room of optimization • Side effect or state is essential in some cases (I/O, GUI)
  3. Immutability Immutability https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf Functional programmers argue that there are great

    material benefits - that a functional programmer is an order of magnitude more productive than his conventional counterpart, because functional programs are an order of magnitude shorter. Yet why should this be? The only faintly plausible reason one can suggest on the basis of these “advantages” is that conventional programs consist of 90% assignment statements, and in functional programs these can be omitted!
  4. First-class and higher-order functions • map • reduce • filter

    "Richard Waters (1979) developed a program that automatically analyzes traditional Fortran programs, viewing them in terms of maps, filters, and accumulations. He found that fully 90 percent of the code in the Fortran Scientific Subroutine Package fits neatly into this paradigm."
  5. Strict vs non-strict (lazy) evaluation at least 6980 times faster

    (0.382 sec in for-loop with array) https://github.com/k-ori/Introduction-to-FP-playground/blob/master/lazyStreamTests.swift
  6. • Swift: Strict evaluation + Lazy evaluation library • Haskell:

    Lazy evaluation by default Strict vs non-strict (lazy) evaluation
  7. Type systems • Algebraic data type • product types (A

    X B) • sum types (A | B) Noodle Food = Ramen (Noodle (Thin | Thick) x Soup (Salt | Soy sauce)) | Pasta (Noodle (Thin | Thick) x Sauce (Tomato | Basil)) | Pho (Noodle (Thin | Thick) x Soup (Salt | Soy sauce)) Complicated type can be represented
  8. Case study 1 Let’s build and manipulate linked list From

    “Why Functional Programming Matters” https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf Find code from https://github.com/k-ori/Introduction-to-FP-playground
  9. Case study 2 Let’s implement run-length encoding Find code from

    https://github.com/k-ori/Introduction-to-FP-playground