Share
Embed
Intro to functional programming
My slides to introduce functional programming. I have given couple talks with those.
Michael Pershyn
September 15, 2014
Transcript
28 slides
-
Agenda • What is functional programming • Pros and cons
of functional programming • Use cases • Examples • Touch bigger topics -
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 -
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” -
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 -
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 -
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} -
Scaling and Concurrency • Scaling out (horizontal) vs. Scaling up
(vertical) • Concurrency in space vs. Concurrency in time -
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. -
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 -
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) -
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 -
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 -
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! -
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 -
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 -
The map function a b c ... s1 s2 f(a)
f(b) f(c) ... s2 = s1.map(f) -
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 ... -
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), ...) -
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)) -
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]}) -
Example 3 Finding friends of friends class Person .. public
Set<Person> friendOfFriends() { return friends.stream() .flatMap(friend -> friend.getPerson().friends.stream()) .map(Friend::getPerson) .filter(f -> f != this) .collect(Collectors.toSet()); } -
Example 4 Finding friends of friends (->> people (sort-by #(distance-from
“21231” %)) (take 100) (filter #(< 20 (:age %) 30) (map :friends) (reduce set/union #{})) -
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 http://www.ibm.com/developerworks/library/wa-javascript/index.html • The Joy of Clojure book by Michael Fogus and Chris Houser • Clojure – the JFDI language – https://docs.google.com/presentation/d/15-7qFy6URdE7Owi2LitkQI_OHBu1AFWPUwHxgBc- O4E/edit#slide=id.p • Search internet about functional programming techniques in your language. It's out there.