The document discusses the key concepts of functional programming including:
- Functional programming uses functions as building blocks and avoids mutable state and side effects.
- Pure functions, immutability, recursion, and function composition are important characteristics.
- Functional programming is well-suited for concurrency since immutable data prevents data races.
- Some benefits of functional programming include simpler code for complex problems, increased correctness from avoiding side effects, and ease of parallelization for concurrency.
How to Troubleshoot Apps for the Modern Connected Worker
Â
Why functional programming in C# & F#
1. OOP makes code understandable by encapsulating
moving parts. FP makes code understandable by
eliminating moving parts.
Riccardo Terrell â Silicon Valley Code Camp
2014
â Michael Feathers
(author of Working with Legacy
Code)
2. Agenda
History and influence of Functional Programming
Functional vs Imperative Programming
What is Functional Programming
Functional Programming characteristics
Why Functional Programming
3. History
LISP
ISWIM
APL
ML
1973
FP
1958 1966
1962
1977
2005F# Clojure
1988Haskell
Scala 2003
2007
Ocam
1996
l
1930
-ish
1986Erlang
Îť
4. Functional Programming
Influence
ď¨ Continue Evolution of GC â Lisp ~1958
ď¨ Generics â ML ~ 1973
ď¨ In early 1994, support for lambda, filter, map, and reduce was added to
Python
ď¨ List comprehension - Linq in C# 3.0 and Java 8
ď¨ First-class functions were also introduce Visual Basic 9, C# and C++ 11
ď¨ Java 8 supports lambda expressions as a replacement for anonymous
classes
ď¨ Is Lazy Evaluation is part of the main stream languages such as C#
ď¨ Type Inference, example is the âvarâ keyword in C#
Programming in a functional style can also be accomplished in languages that aren't
5. Objectives
ď¨ Use functions as building block and composition to solve
complex problem with simple code
ď¨ Immutability and Isolation are your best friends to write
concurrent application
ď¤ Concurrency and reliability are becoming more and more required,
FP will help you!
ď¨ Functional and imperative styles should NOT stand in opposition
âŚ
⌠they should COEXIST
ď¤ Poly-paradigm programming is more powerful and effective
than polyglot programming
6. FP vs OOP the Paradigm-
Switch
Functional Programming may look
scary for an object-oriented
developer because of all the strange
buzzwords like Functor, Referential
Transparency, Monads, etc., but they
are really just unfamiliar terms.
Object-oriented programming can be
a scary one with all its concepts, e.g.
polymorphism, encapsulation,
inheritance, covariance, etc.
?@#?%!
7. FP OOP Key Concepts
ď¨ Functional Programming is different in many ways from a
standard imperative language, but there are a few major
differences that are particularly important to understand:
Function-oriented
not
object-oriented
Expressions
rather than
Statements
Immutable
rather than
mutable
8. What is "Functional
Programming?"
Functional programming is just a style, is a programming paradigm
that treats computation as the evaluation of functions and avoids
state and mutable dataâŚ
ď¨ âFunctions as primary building blocksâ (first-class functions)
ď¨ programming with âimmutableâ variables and assignments, no state
ď¤ Programs work by returning values instead of modifying data
9. What is "Functional
Programming?"
Functional programming is so called because a program consists entirely of
functions.
First class
Higher-Order
Functions
Immutability
Declarative
Îť
⌠is all about functions! Identifying an abstraction and building a function,
use existing functions to build more complex abstractions, pass existing
functions to other functions to build even more complex abstractions
11. Higher-Order functions
A higher-order function is a function that takes another function as a
parameter, or a function that returns another function as a value, or a
function which does both.
12. Pure Functions - Properties and
Benefits
ď¨ A function always gives the same output value for a given
input value
ď¤ I can then cache the result
ď¨ A Pure Function has no side effects
ď¨ Pure functions can be executed in parallel
ď¨ The function does not rely on any external state
ď¤ Increased readability and maintainability
ď¨ Pure functions can more easily isolated
ď¤ easier testing and debugging
17. Unwanted Side Effects are Evil!
Side effects arenât badâŚ
unwanted side effects are EVIL
and the root of many bugs!
One of the biggest advantages with functional
programming is that the order of execution of âside
effect free functionsâ is not important.
⌠âside effect free functionsâ are
easy to parallelize
18. Currying
Curry is a technique in which a function is applied to its
arguments one at a time, with each
application returning a new function
that accepts the next argument
Higher-order function enable
Partial Application and Currying
19. Partial Application
Partial Application refers to the process of fixing a
number of arguments to a function, producing
another function of smaller arity
With both currying and partial application, you supply argument values and return a
function thatâs invokable with the missing arguments. But currying a function returns
the next function in the chain, whereas partial application binds argument values to
values that you supply during the operation, producing a function with a smaller arity
20. Immutability
ď¨ Immutability is very important characteristic of FP but mostly is about transformation of
state⌠⌠Immutable data forces you to use a âtransformationalâ approach
ď¨ When youâre writing programs using
immutable types, the only âthing a method
can do is return a result, it canât modify the
state of any objects
ď¨ Immutable data makes the code predictable
is easier to work
ď¨ Prevent Bugs
ď¨ Concurrency is much simpler, as you donât
have to worry about using locks to avoid
update conflicts
ď¤ Automatic thread-safe, controlling mutable state in
22. Function Composition
Function Composition - Building with composition. Composition is the
'glue' that allows us build larger systems from smaller ones. This is the very
heart of the functional style. Almost every line of code is a composable
expression. Composition is used to build basic functions, and then functions
that use those functions, and so on.
Composition â in the form of passed parameters plus first-class functions
23. Using functions as building
blocks
ď¨ A well-known principle of good design is to create a set of basic
operations and then combine these building blocks in various
ways to build up more complex behaviors
24. Compose Mario
Mario game sample, based on functional reactive Elm script (http://elm-lang.
org/edit/examples/Intermediate/Mario.elm)
The functions that depend on keyboard take the current keyboard state as the first argument. This is
represented as a tuple int*int (dir) consisting of x and y directions.
The step function of the game takes previous Mario value and returns a new one. It is composed from 4
functions that represent different aspects of the game.
27. Lazy Evaluation - Strict & Non-Strict
Evaluation
ď¨ Lazy evaluation deferral of expression evaluation for as long
as possible until absolutely needed
ď¨ Languages can be categorized as strict (eagerly evaluating
all expressions) or lazy (deferring evaluation)
ď¤ Strict evaluation always fully evaluates
function arguments before invoking the
function
ď¤ Lazy evaluation does not evaluate function
arguments unless their values are required to
evaluate the function call itself
28. Recursion is the new iteration
ď¨ In functional programming âiterationâ is ~usually~ accomplished via
recursion
ď¤ Recursive function invoke themselves, Tail recursion is optimized by
compiler avoiding to maintain a stack ~stack over flow!
29. Recursion is the new iteration
ď¨ In functional programming âiterationâ is ~usually~ accomplished via
recursion
34. Why Functional Programming?
ď¨ Changes the way you think about programming and problem
solving
ď¨ Functional Programming promotes Composition and Modularity
ď¨ Simple Code for Complex Problems
ď¨ Declarative programming style
ď¨ Concurrency, FP is easy to parallelize
ď¤ Locking vs. immutable memory
ď¨ Conciseness, less code (no null checking)
ď¨ Correctness & Reduced bugs (immutability)
ď¨ Rapid Prototyping
35. Concurrency
Modern computers come with
multiple processors, each
equipped with multiple cores, but
the single processor is slower
than used to be! Mooreâs law
(http://en.wikipedia.org/wiki/Moore's_law)
⌠to achieve great performances the
application must be leveraging a
Concurrent Model
36. Concurrency
There is a problemâŚ
the free lunch is over
ďą Programs are not doubling in speed every
couple of years for free anymore
ďąWe need to start writing code to take
advantage of many cores
37. Concurrency⌠jams to avoid!
Parallel, asynchronous,
concurrent, and reactive
programs bring many
challenges because these
programs are nearly always
nondeterministic
ďŽ This makes debugging/testing
challenging
ďŽ Deadlocking
ďŽ Not easy to program
38. Concurrency
ď¨ Imperative and traditional
programming styles gives
us bad headaches
ď¤ Itâs difficult to turn existing sequential
code into parallel code
ď¤ Using shared state and locks is
difficult
ďŽ different threads can change the same
39. Concurrency
ď¨ Functional programming feels
good:
ď¤ Thanks to the immutability (and isolation),
we avoid introducing race conditions and we
can write lock-free code.
ď¤ Using a declarative programming style
we can introduce parallelism into
existing code easily. We can replace a
few primitives that specify how to
combine commands with version that
executes commands in parallel
40. Concurrent Model Programming
An Agent is an independent computational
entity which contains a queue, and receives
IMMUTABILITY +
ISOLATION +
and processes messages
DECLARATIVE PROGRAMMING =
------------------------------------------------
It provides immutability and isolation
BEST CONCURRENT MODEL
PROGRAMMING
(it enforces coarse-grained isolation through message-passing)
43. Pipeline Processing
ď¨ Pipeline according to Wikipedia:
ď¤ A pipeline is a set of data processing elements
connected in series, so that the output of one element
is the input of the next one. The elements of a pipeline
are often executed in parallel or in time-sliced fashion;
in that case, some amount of buffer storage is often
inserted between elements
46. Pipeline Processing
ď¨ Values processed in multiple steps
ď¤ Worker takes value, processes
it, and sends it
ď¤ Worker is blocked when source
is empty
ď¤ Worker is blocked when target
is full
ď¤ Steps of the pipeline run in
parallel
49. Functional Job Trend
Functional languages are
sprouting not just on the
JVM where the two most
interesting new languages
are Scala and Clojure, but
also on the .NET platform,
where F# is a first-class
citizen
http://www.itjobswatch.co.uk
50. Wrap-Up
ď¨ Use functions as building block and composition to solve complex
problem with simple code
ď¨ Immutability and Isolation are your best friends to write concurrent
application
ď¤ Concurrency and reliability are becoming more and more required, FP will help you!
ď¨ Functional and imperative styles should NOT stand in opposition
butâŚ
âŚthey should COEXIST
ď¤ Poly-paradigm programming is more powerful
and effective than polyglot programming
51. Q & A ?
The tools we use have a profound (and devious!) influence on our
thinking habits, and, therefore, on our thinking abilities.
-- Edsger Dijkstra
53. How to reach me
github.com/DCFsharp
meetup.com/DC-fsharp/
@DCFsharp
rterrell@microsoft.com
Hinweis der Redaktion
Recursion to do not modify the list
Many people find functional programming elegant or even beautiful, but thatâs hardly a good reason to use it in a commercial environment.
Elegance doesnât pay the bills, sad to say.
One of the big reason for coding in a functional style is that it makes you and your team more productive.