Intro to functional programming

Intro to functional programming

My slides to introduce functional programming. I have given couple talks with those.


Michael Pershyn

September 15, 2014


  1. Intro to Functional Programming Michael Pershyn @pershyn

  2. Goal Introduce FP and show how it solves problems

  3. Agenda • What is functional programming • Pros and cons

    of functional programming • Use cases • Examples • Touch bigger topics
  4. What is Functional Programming Paradigm The are also Imperative and

    Logic paradigms. Othrogonal to it – object oriented programming. - Hey, what is Paradigm? - A distinct concept or thought pattern
  5. Imperative world • modifying mutable variables – memory cells •

    using assignments – load and store instructions • (jump) control structures – if-then-else, loops, breaks, continue and return Von Neumann computer It has serious bottleneck – scaling. “One tends to conceptualize data structures word-by-word”
  6. World is changing • 15 years of exponential CPU's frequencies

    grow ended somewhere in 2005 • Moore's law now achieved by scaling out and not scaling up – Same speed, more cores • Demand for processing resources still grows • Software world not yet adapted – Hey, we still have COBOL
  7. Concurrent models • Parallel programming – Execute programs faster on

    parallel software – CUDA, OpenCL, etc • Concurrent programming – Manage concurrent threads explicitly – Mutexes, Semaphores, etc Both are hard
  8. Root of the Problem Non-determinism caused by concurrent threads accessing

    mutable state Some resource x; A(): x = x + 1; B(): x = x * 2; If x was 0 Result is undefned: {289, 3, 6561}
  9. Space vs Time

  10. Identity vs State … vs Mutable State

  11. Scaling and Concurrency • Scaling out (horizontal) vs. Scaling up

    (vertical) • Concurrency in space vs. Concurrency in time
  12. So, was it all wrong? It worked. But, not the

    way to go. People were telling this from the beginning. And not just telling. Lets check the history.
  13. History 1958 Lisp 1975-77 ML, FP, Scheme 1978 Smalltalk 1986

    Standard ML 1990 Haskell, Erlang 1999 XSLT 2000 OCaml 2003 Scala, XQuery 2005 F# 2007 Clojure
  14. So, what is FP Paradigm? • Functions! As frst class

    citizens • Immutability • Promote concurrency in space • FP is about going away from Von Neumann Model of calculations in Lambda Calculus direction • That means trying to describe what should be done (functions), and not how (instructions)
  15. Some FP techniques • Lazyness by design • Lambdas and

    Closures • Map, reduce, zip, fatMap • Partial function application and currying • New collections – Parallel (made for map) – Generators, unlimited collections, etc • FRP - data fows and the propagation of change made on functions • Advanced Concurrency – STM – Futures – Atoms – Agents
  16. Future is now • Clojure: all the functional paradigms on

    JVM, CLR, JavaScript VMs, lisp dialect • Scala: java-like functional language, inter-operable with java, runs on JVM, supports imperative style as well • Java8: well, they became functional in new Java (functions are frst-class now, lambda expression, parallel collections) • C++ 11~14: lambdas (replace functors), there are immutable struct implemented on shared_ptr, std::bind, std::transform • JS: closures are used, currying is there, FRP can be done in javascript
  17. Pros and Cons of FP • Stateless programs; No side

    efects • Concurrency • Programs are usually shorter and easier to read – 한국어도 읽기 쉽다 . 심각 . • Productivity vs Performance - hey, they were just selling OOP back then, it’s marketing!
  18. Use cases • UI, Reactive programming, data-fows • Concurrent and

    distributed systems – hadoop, real-time processing, multi-threads programs • Big programs – in FP style there are usually 3x-10x less code • Basically, all the languages starting to to have functional features and mutate to have functional style • Most probably you will be using FP before you know it
  19. Bad use cases • Low-level work, when our main domain

    model is von Neuman computer – kernels, drivers, controllers, etc • Rewriting huge systems that work and are scalable • When you have all your expertise in imperative world and scaling out is not needed • Complexity is not planned to be big – small single-threaded programs, scripts, no UI
  20. The map function a b c ... s1 s2 f(a)

    f(b) f(c) ... s2 =
  21. The fatMap function a b ... s1 s2 f(a) 0

    f(a) 1 f(b) 0 f(b) 1 s2 = s1.fatMap(f) f(b) 2 ...
  22. The reduce function s1 a b c d x =

    s1.reduce(initial, f) e ... f(f(f(f(f(f(initial, a), b), c), d), e), ...)
  23. Examples • C#, imperative style int sum = 0; foreach

    (int i in mylist) { sum += (i + 1); } • C#, functional style result = mylist.Select(i => i + 1).Sum(); • Clojure (reduce + (map inc mylist))
  24. Examples 2 from random import random def move_cars(car_positions): return map(lambda

    x: x + 1 if random() > 0.3 else x, car_positions) def output_car(car_position): return '-' * car_position def run_step_of_race(state): return {'time': state['time'] - 1, 'car_positions': move_cars(state['car_positions'])} def draw(state): print '' print '\n'.join(map(output_car, state['car_positions'])) def race(state): draw(state) if state['time']: race(run_step_of_race(state)) race({'time': 5, 'car_positions': [1, 1, 1]})
  25. Example 3 Finding friends of friends class Person .. public

    Set<Person> friendOfFriends() { return .flatMap(friend -> friend.getPerson() .map(Friend::getPerson) .filter(f -> f != this) .collect(Collectors.toSet()); }
  26. Example 4 Finding friends of friends (->> people (sort-by #(distance-from

    “21231” %)) (take 100) (filter #(< 20 (:age %) 30) (map :friends) (reduce set/union #{}))
  27. Links • Martin Odersky talks, books and course on courseera.

    Joel Spolsky blog, other blogs • Java8, C++11-14 release notes • Chris Richardson presentation on Functional Programming • Use functional programming techniques to write elegant JavaScript • The Joy of Clojure book by Michael Fogus and Chris Houser • Clojure – the JFDI language – O4E/edit#slide=id.p • Search internet about functional programming techniques in your language. It's out there.
  28. Thank you! Questions?