SlideShare a Scribd company logo
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?

More Related Content

What's hot (19)

PPTX
Flow control in Python
Md. Shafiuzzaman Hira
 
PPTX
Eurosport's Kodakademi #2
Benjamin Baumann
 
PDF
Functional programming scala_mod
Kishore
 
PDF
Functional Programming For All - Scala Matsuri 2016
Zachary Abbott
 
PPTX
Unit 3.1 Algorithm and Flowchart
Bom Khati
 
PPTX
Language translation system p
anassatti5
 
PDF
Extending Machine Translation in AEM
Vivek Sachdeva
 
PPTX
Programming Paradigm & Languages
Gaditek
 
PPTX
How To Write a Testable Code
OPIN Software Inc.
 
PDF
Introduction to Machine translation - AEM
Vivek Sachdeva
 
PDF
Erlang workshopdrammen
Reidar Sollid
 
PPTX
PART 10 - Python Tutorial | Functions In Python With Examples
Shivam Mitra
 
PDF
Xtend - better java with -less- noise
Neeraj Bhusare
 
PPTX
Introduction to Functional programming
Ny Fanilo Andrianjafy, B.Eng.
 
PDF
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
PPTX
PART 0 - Python Tutorial | Why should you learn python
Shivam Mitra
 
PDF
Cis 1403 lab5_loops
Hamad Odhabi
 
PPTX
Managing state in modern React web applications
Jon Preece
 
Flow control in Python
Md. Shafiuzzaman Hira
 
Eurosport's Kodakademi #2
Benjamin Baumann
 
Functional programming scala_mod
Kishore
 
Functional Programming For All - Scala Matsuri 2016
Zachary Abbott
 
Unit 3.1 Algorithm and Flowchart
Bom Khati
 
Language translation system p
anassatti5
 
Extending Machine Translation in AEM
Vivek Sachdeva
 
Programming Paradigm & Languages
Gaditek
 
How To Write a Testable Code
OPIN Software Inc.
 
Introduction to Machine translation - AEM
Vivek Sachdeva
 
Erlang workshopdrammen
Reidar Sollid
 
PART 10 - Python Tutorial | Functions In Python With Examples
Shivam Mitra
 
Xtend - better java with -less- noise
Neeraj Bhusare
 
Introduction to Functional programming
Ny Fanilo Andrianjafy, B.Eng.
 
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
PART 0 - Python Tutorial | Why should you learn python
Shivam Mitra
 
Cis 1403 lab5_loops
Hamad Odhabi
 
Managing state in modern React web applications
Jon Preece
 

Similar to Introduction to Functional Programming (20)

PPTX
When life gives you functions make functional programs!
Aaron Levin
 
PPTX
Functional programming
PiumiPerera7
 
PPTX
Intro f# functional_programming
Mauro Ghiani
 
PDF
Introduction to functional programming
Konrad Szydlo
 
PPT
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
PPT
Introductory func prog
Oleksandr Khomenko
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
ODP
Functional programming
S M Asaduzzaman
 
PPTX
Functional Programming
Ryan Riley
 
PDF
Functional Programming #FTW
Adriano Bonat
 
PDF
Becoming Functional Steps For Transforming Into A Functional Programmer Joshu...
chelliidzia
 
PPTX
Dev Concepts: Functional Programming
Svetlin Nakov
 
PPTX
Functional Programming Introduction
Roberto Lopez
 
PDF
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
PPTX
Functional Programming Fundamentals
Shahriar Hyder
 
PDF
Functional programming
ijcd
 
KEY
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
PPTX
The joy of functional programming
Steve Zhang
 
PDF
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
PPTX
Functional Programming.pptx
KarthickT28
 
When life gives you functions make functional programs!
Aaron Levin
 
Functional programming
PiumiPerera7
 
Intro f# functional_programming
Mauro Ghiani
 
Introduction to functional programming
Konrad Szydlo
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Introductory func prog
Oleksandr Khomenko
 
Why functional programming in C# & F#
Riccardo Terrell
 
Functional programming
S M Asaduzzaman
 
Functional Programming
Ryan Riley
 
Functional Programming #FTW
Adriano Bonat
 
Becoming Functional Steps For Transforming Into A Functional Programmer Joshu...
chelliidzia
 
Dev Concepts: Functional Programming
Svetlin Nakov
 
Functional Programming Introduction
Roberto Lopez
 
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Functional Programming Fundamentals
Shahriar Hyder
 
Functional programming
ijcd
 
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
The joy of functional programming
Steve Zhang
 
Introduction to Functional Programming
Hoàng Lâm Huỳnh
 
Functional Programming.pptx
KarthickT28
 
Ad

Recently uploaded (20)

PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Executive Business Intelligence Dashboards
vandeslie24
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Import Data Form Excel to Tally Services
Tally xperts
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Ad

Introduction to Functional Programming

  • 4. A Parable By Anton van Straaten (http://bit.ly/2fDGPOe)
  • 6. 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)
  • 7. The OO guidelines point to functional programming!
  • 9. Clean Code • Keep functions small • Don’t repeat yourself • Functions should accept no more than 3 parameters • Do one thing • Avoid side-effects
  • 10. SOLID Principles • Single Responsibility • Open-Closed • Liskov Substitution • Interface Segregation • Dependency Inversion SOLID: The Next Step is Functional Mark Seemann http://bit.ly/UbqcZr
  • 11. FP and OOP are not mutually exclusive
  • 12. 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
  • 13. You’re Probably Already Doing It • LINQ? • jQuery? • React/Redux?
  • 14. 3 Pillars of Functional Programming • Functional Purity/Controlling Side Effects • Favoring Expressions over Statements • Treating Functions as Data
  • 15. 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
  • 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 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; }
  • 18. 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.
  • 19. 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!
  • 20. Example: Conditional Operator var category = ""; if(input % 2 == 0) { category = "even"; } else { category = "odd"; } var category = input % 2 == 0 ? "even" : "odd";
  • 21. Example: Using Statement var category = ""; using(var classifier = new classifier()) { category = classifier.Classify(input); }
  • 22. 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));
  • 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 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.
  • 26. 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
  • 27. Wait You said this was an old concept why are we going back? • Code Longevity • It’s easier to write
  • 28. 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.
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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.
  • 33. 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.
  • 34. 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
  • 35. 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
  • 36. 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

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.