KEMBAR78
Introduction to Functional Programming | PPTX
An Introduction
to Functional
Programming
DAVE FANCHER
@DAVEFANCHER | DAVE@DAVEFANCHER.COM
About Me
https://twitter.com/richardadalton/status/707984880861364225
A Parable
By Anton van Straaten (http://bit.ly/2fDGPOe)
What is
Functional
Programming?
FP is not new.
• Based on lambda calculus developed in 1930’s
• Has been used as far back as the 1950’s (LISP and IPL)
The OO guidelines
point to functional
programming!
Clean Code
Clean Code
• Keep functions small
• Don’t repeat yourself
• Functions should accept no
more than 3 parameters
• Do one thing
• Avoid side-effects
SOLID Principles
• Single Responsibility
• Open-Closed
• Liskov Substitution
• Interface Segregation
• Dependency Inversion
SOLID: The Next Step is Functional
Mark Seemann
http://bit.ly/UbqcZr
FP and OOP are not
mutually exclusive
OO vs FP
OO makes code
understandable by
encapsulating moving parts.
FP makes code
understandable by minimizing
moving parts.
Michael Feathers
http://bit.ly/1HOVBSM
You’re Probably Already Doing It
• LINQ?
• jQuery?
• React/Redux?
3 Pillars of
Functional Programming
• Functional Purity/Controlling Side Effects
• Favoring Expressions over Statements
• Treating Functions as Data
What is Functional Purity?
• Determinism. Functions depend only upon their input, and given a certain set of
inputs will always have the same output.
• Not dependent on state of outside object that may change.
• Often written as static functions as a means to enforce functional purity
• Referential Transparency
◦ X = 3
◦ X + 2 = 5
◦ 3 + 2 = 5
Taming Side Effects
• Side effects are changes to state outside of the current function
• Software generally needs some side effects (I/O)
• Generally fixed with immutability
• Code smells:
• void functions indicate a side-effect
• Parameterless functions indicate dependency on external state
Purity and Impurity
public class Impurity{
public int i { get; set; }
public int Increment() => i = i + 1;
}
public static class Purity{
public static int Increment(int i) => i + 1;
}
Emphasizing Expressions
• Expressions always return a value.
• Small units of logic taking in only what
is needed for computation and
returning the result.
• Expressions make composition much
easier.
• Lego instructions are a wonderful
example of expressions.
Tips for Emphasizing Expressions in
a Statement-Based World
• Minimize the use of void methods
• Accept input and return output wherever possible
• If an expression-based alternative exists, use it!
• If an expression-based alternative doesn’t exist, make one!
Example: Conditional Operator
var category = "";
if(input % 2 == 0)
{
category = "even";
}
else
{
category = "odd";
}
var category =
input % 2 == 0
? "even"
: "odd";
Example: Using Statement
var category = "";
using(var classifier = new classifier())
{
category = classifier.Classify(input);
}
Using Function
public static U Dispose<T, U>(Func<T> factory, Func<T, U> fn)
where T : IDisposable
{
using(var disposable = factory())
{
return fn(disposable);
}
}
var category =
Disposable.Using(
() => new Classifier(),
classifier => classifier.Classify(input));
Functions as Data
• Functions treated like any other data structure.
• Higher order functions accept or return functions as data
• Central concept of partial application and currying
Lambda Expressions/
Arrow Functions
• Anonymous functions passed into a method.
• Can be assigned as a property in some languages.
• Is the namesake for lambda calculous
• Not able to have recursive lambda functions
• Used only in the closure they are defined in
Why do Programmers Start
Functional Programming
• Functional lends itself to reusable code.
• Small functions with only a single purpose
• Simplicity of code.
• Functional programs often made of a single expression that appears to have one line of
code in it.
Why LINQ?
• LINQ is made of functional methods that take the tedium out of working with
collections of data
• Functional extension methods for IEnumerable that accept a function as an argument
Wait You said this was an old concept
why are we going back?
• Code Longevity
• It’s easier to write
Why is it easier to write?
• It isn’t always easier to write.
• Programming in the functional style will make your code blocks smaller and more
reusable.
• Since you always know what the function will do if it’s a pure function once you have
tested it you know it will always work
• Because of using functions as data functions often have a natural interface you can
utilize for unit testing.
Debugging
• Managing program state causes debugging to be more difficult
• Root-cause of most defects is from state management or side effects
• The emphasis on functional purity and expression-based programming generally
results in fewer defects
• When a language does not allow an object to be null, NullReferenceExceptions
cannot happen.
© 2017 ALASKA AIRLINES - CONFIDENTIAL 29
Functional Languages
• Many languages are actually multi-paradigm
• Languages that allow functions as first-class citizens can be used in a functional
manner
• Some languages are better suited to functional programming than others
Purely Functional
& Functional-First Languages
• Meant to be used in a functional style
• Haskell
• F#
• Idris
• Elm
• Agda
• Similarities
• Objects immutable
• Methods usually have a single entry point and a single return value
• Usually safely able to adopt parallelization by default
• Strong static typing
Languages that can be used in a
functional style
• Almost any language can be used in a functional style
• The biggest requirement for functional programming is that the language must allow
functions as first class objects
• Attention must be given to make sure your program will function in a functional
manner.
Languages that can be functional
(with a little work)
• C/C++, Java
• Languages that use pass by value as a default
• Since functions cannot be simply passed function pointers must be used.
Which Functional Language
Should I Use?
• The one you’re already using!
• Purely functional languages are extremely good for mathematical computation
• IO heavy applications aren’t necessarily well suited to functional languages, but can
still be written in a functional style
A language that doesn't affect the way you think
about programming, is not worth knowing.
– Alan Perlis, Epigrams on Programming
Ok so lets recap, what is functional
programming?
• A mindset
• Changes the way programmers thing away from what do we use to build our
programs, to something closer to what we want our programs to do.
• A paradigm designed to eliminate state management for objects
On Functional Style
No matter what language you
work in, programming in a
functional style provides
benefits. You should do it
whenever it is convenient, and
you should think hard about
the decision when it isn't
convenient.
John Carmack
http://ubm.io/1U4zArZ
QUESTIONS?

Introduction to Functional Programming

  • 1.
    An Introduction to Functional Programming DAVEFANCHER @DAVEFANCHER | DAVE@DAVEFANCHER.COM
  • 2.
  • 3.
  • 4.
    A Parable By Antonvan Straaten (http://bit.ly/2fDGPOe)
  • 5.
  • 6.
    FP is notnew. • Based on lambda calculus developed in 1930’s • Has been used as far back as the 1950’s (LISP and IPL)
  • 7.
    The OO guidelines pointto functional programming!
  • 8.
  • 9.
    Clean Code • Keepfunctions small • Don’t repeat yourself • Functions should accept no more than 3 parameters • Do one thing • Avoid side-effects
  • 10.
    SOLID Principles • SingleResponsibility • Open-Closed • Liskov Substitution • Interface Segregation • Dependency Inversion SOLID: The Next Step is Functional Mark Seemann http://bit.ly/UbqcZr
  • 11.
    FP and OOPare not mutually exclusive
  • 12.
    OO vs FP OOmakes code understandable by encapsulating moving parts. FP makes code understandable by minimizing moving parts. Michael Feathers http://bit.ly/1HOVBSM
  • 13.
    You’re Probably AlreadyDoing It • LINQ? • jQuery? • React/Redux?
  • 14.
    3 Pillars of FunctionalProgramming • Functional Purity/Controlling Side Effects • Favoring Expressions over Statements • Treating Functions as Data
  • 15.
    What is FunctionalPurity? • Determinism. Functions depend only upon their input, and given a certain set of inputs will always have the same output. • Not dependent on state of outside object that may change. • Often written as static functions as a means to enforce functional purity • Referential Transparency ◦ X = 3 ◦ X + 2 = 5 ◦ 3 + 2 = 5
  • 16.
    Taming Side Effects •Side effects are changes to state outside of the current function • Software generally needs some side effects (I/O) • Generally fixed with immutability • Code smells: • void functions indicate a side-effect • Parameterless functions indicate dependency on external state
  • 17.
    Purity and Impurity publicclass Impurity{ public int i { get; set; } public int Increment() => i = i + 1; } public static class Purity{ public static int Increment(int i) => i + 1; }
  • 18.
    Emphasizing Expressions • Expressionsalways return a value. • Small units of logic taking in only what is needed for computation and returning the result. • Expressions make composition much easier. • Lego instructions are a wonderful example of expressions.
  • 19.
    Tips for EmphasizingExpressions in a Statement-Based World • Minimize the use of void methods • Accept input and return output wherever possible • If an expression-based alternative exists, use it! • If an expression-based alternative doesn’t exist, make one!
  • 20.
    Example: Conditional Operator varcategory = ""; if(input % 2 == 0) { category = "even"; } else { category = "odd"; } var category = input % 2 == 0 ? "even" : "odd";
  • 21.
    Example: Using Statement varcategory = ""; using(var classifier = new classifier()) { category = classifier.Classify(input); }
  • 22.
    Using Function public staticU Dispose<T, U>(Func<T> factory, Func<T, U> fn) where T : IDisposable { using(var disposable = factory()) { return fn(disposable); } } var category = Disposable.Using( () => new Classifier(), classifier => classifier.Classify(input));
  • 23.
    Functions as Data •Functions treated like any other data structure. • Higher order functions accept or return functions as data • Central concept of partial application and currying
  • 24.
    Lambda Expressions/ Arrow Functions •Anonymous functions passed into a method. • Can be assigned as a property in some languages. • Is the namesake for lambda calculous • Not able to have recursive lambda functions • Used only in the closure they are defined in
  • 25.
    Why do ProgrammersStart Functional Programming • Functional lends itself to reusable code. • Small functions with only a single purpose • Simplicity of code. • Functional programs often made of a single expression that appears to have one line of code in it.
  • 26.
    Why LINQ? • LINQis made of functional methods that take the tedium out of working with collections of data • Functional extension methods for IEnumerable that accept a function as an argument
  • 27.
    Wait You saidthis was an old concept why are we going back? • Code Longevity • It’s easier to write
  • 28.
    Why is iteasier to write? • It isn’t always easier to write. • Programming in the functional style will make your code blocks smaller and more reusable. • Since you always know what the function will do if it’s a pure function once you have tested it you know it will always work • Because of using functions as data functions often have a natural interface you can utilize for unit testing.
  • 29.
    Debugging • Managing programstate causes debugging to be more difficult • Root-cause of most defects is from state management or side effects • The emphasis on functional purity and expression-based programming generally results in fewer defects • When a language does not allow an object to be null, NullReferenceExceptions cannot happen. © 2017 ALASKA AIRLINES - CONFIDENTIAL 29
  • 30.
    Functional Languages • Manylanguages are actually multi-paradigm • Languages that allow functions as first-class citizens can be used in a functional manner • Some languages are better suited to functional programming than others
  • 31.
    Purely Functional & Functional-FirstLanguages • Meant to be used in a functional style • Haskell • F# • Idris • Elm • Agda • Similarities • Objects immutable • Methods usually have a single entry point and a single return value • Usually safely able to adopt parallelization by default • Strong static typing
  • 32.
    Languages that canbe used in a functional style • Almost any language can be used in a functional style • The biggest requirement for functional programming is that the language must allow functions as first class objects • Attention must be given to make sure your program will function in a functional manner.
  • 33.
    Languages that canbe functional (with a little work) • C/C++, Java • Languages that use pass by value as a default • Since functions cannot be simply passed function pointers must be used.
  • 34.
    Which Functional Language ShouldI Use? • The one you’re already using! • Purely functional languages are extremely good for mathematical computation • IO heavy applications aren’t necessarily well suited to functional languages, but can still be written in a functional style A language that doesn't affect the way you think about programming, is not worth knowing. – Alan Perlis, Epigrams on Programming
  • 35.
    Ok so letsrecap, what is functional programming? • A mindset • Changes the way programmers thing away from what do we use to build our programs, to something closer to what we want our programs to do. • A paradigm designed to eliminate state management for objects
  • 36.
    On Functional Style Nomatter what language you work in, programming in a functional style provides benefits. You should do it whenever it is convenient, and you should think hard about the decision when it isn't convenient. John Carmack http://ubm.io/1U4zArZ
  • 37.

Editor's Notes

  • #5 A venerable master was walking with his student. Hoping to prompt the master into a discussion, the student said "Master, I have heard that objects are a very good thing - is this true?" The master looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures.“ Chastised, the student took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On their next walk the student attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." The master responded by hitting the student with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, the student became enlightened.
  • #6 Ask the audience for 2 or 3 definitions
  • #8 All of these things ultimately guide us to programming in a functional style as Mark Seemann described this nicely in a blog post titled SOLID: the next step is functional which I highly encourage you to read
  • #9 Here’s another thing that points to FP: Not talking about things like naming or comments but the others, keeping functions small, not repeating yourself, limiting the # of parameters, doing one thing, and avoiding side effects also seem to follow the spirit of the functional themes we’ve discussed.
  • #10 Here’s another thing that points to FP: Not talking about things like naming or comments but the others, keeping functions small, not repeating yourself, limiting the # of parameters, doing one thing, and avoiding side effects also seem to follow the spirit of the functional themes we’ve discussed.
  • #11 Following the SOLID principles is one way we try to make OO manageable. When we take Single-responsibility and interface segregation to the extreme our code starts looking quite functional.
  • #12 Despite perception, the FP/OOP dichotomy is not a mutually exclusive proposition. What’s more is that you’re probably already using FP. LINQ JavaScript (what’s the basic code organization unit?)
  • #13 Quote from Twitter In OO we think of object hierarchies and behavior; constant state management Now I think of independent functions and data Focusing on what data functions need to produce the desired result That means more static classes and less inheritance. It also means more liberal use of delegation
  • #15 A good, single definition of functional programming is difficult to pin down but most definitions tend reduce to three central themes
  • #17 Example of tracking bug where discount wasn’t being applied because a method with a benign-sounding name was deleting the data!
  • #19 Returning a value is easier to test
  • #20 Use the ternary, or conditional operator Discuss composability of single-input functions
  • #29 It often is easier to write in a functional style but isn’t always easier. Usually the trade-off for sticking with a functional style result in more resilient code.