SlideShare a Scribd company logo
Functional
Programming
• Functional code is characterised by one thing: the absence of side effects. It
doesn’t rely on data outside the current function, and it doesn’t change data that
exists outside the current function. Every other “functional” thing can be derived
from this property. Any examples of functions with side effects and no side
effects?
• The key to Functional Programming is in the name: functions. FP is about
immutability and composing functions rather than objects.
Functions are first class
• What makes something first class?
Functions are first class
• What makes something first class?

• It can be created on demand

• It can be stored in a data structure

• It can be passed as an argument to a function

• It can be returned as the value of a function
Creating functions on
demand using composition
Find the fifth element of a collection:
(def fifth (comp first rest rest rest rest))
(fifth [1 2 3 4 5])
•comp : Takes a set of functions and returns a fn that is the
composition of those fns
•first: Returns the first item in the collection
•rest: Returns a possibly empty seq of the items after the first.
•Find nth element of a collection using composition?
CREATING FUNCTIONS ON DEMAND USING
PARTIAL FUNCTIONS
((partial + 5) 100 200)
;=> 305
The function partial builds a new function that partially applies the single
argument 5 to the addition function. When the returned partial function is passed
the arguments 100 and 200, the result is their summation plus that of the value 5
captured by partial.
•
USING FUNCTIONS AS DATA
• First-class functions can not only be treated as data; they are data
• It can be stored in a container expecting a piece of data, be it a local, a
reference, collections, or anything able to store a
java.lang.Object.
(defn join
{:test (fn []
(assert
(= (join "," [1 2 3]) "1,3,3")))}
[sep s]
(apply str (interpose sep s)))
•
Higher-order functions
A higher-order function is a function that does at
least one of the following:
• Takes one or more functions as arguments
• Returns a function as a result
Functions as Arguments
(sort-by second [[:a 7], [:c 13], [:b 21]])
;;=> ([:a 7] [:c 13] [:b 21])
Functions as return values
•(complement f)
Takes a fn f and returns a fn that takes the same
arguments as f,
has the same effects, if any, and returns the opposite
truth value.
(def not-empty? (complement empty?))
;; #'user/not-empty?
Pure Functions
Simply put, pure functions are regular functions that, through
convention, conform to the following simple guidelines
• The function always returns the same result, given the same
arguments.
• The function doesn’t cause any observable side effects.
Pure or Impure?
var x = 5;
function addToX(a) {
return a + x;
}
function getLength(array) {
return array.length;
}
•
Pure or Impure?
function add(x, y) {
return x + y;
}
function add(x,y) {
updateDatabase();
return x + y;
}
•
REFERENTIAL TRANSPARENCY
TESTABILITY
If a function is referentially transparent, then it’s easier to reason about and
therefore more straightforward to test. Imagine the confusion should you add
further impure functions based on further external transient values.
OPTIMIZATION
If a function is referentially transparent, then it can more easily be optimized using
techniques such as memoization.
OOPS vs FP
Object-oriented programming (OOP) is a programming paradigm based on
the concept of "objects", which are data structures that contain data, in the
form of fields, often known as attributes; and code, in the form of procedures,
often known as methods
Functional programming is a programming paradigm, a style of building the
structure and elements of computer programs, that treats computation as the
evaluation of mathematical functions and avoids changing-state and mutable
data
OOP vs FP
 the data (the stuff a program knows)
the behaviors (the stuff a program can do to/with that data)
•OOP says that bringing together data and its associated behavior in a
single location (called an “object”) makes it easier to understand how a
program works.
•FP says that data and behavior are distinctively different things and
should be kept separate for clarity.
Let’s say you run a company and you’ve just decided to
give all your employees a $10,000.00 raise. How could
we write a command-line script to make this change?
Approach using OOP
class Employee
def initialize(name, salary)
@name = name
@salary = salary
end
def change_salary(amt)
@salary = @salary + amt
end
def description
"#{@name} makes #{@salary}"
end
end
•
employees = [
Employee.new("Bob", 100000.0),
Employee.new("Jane", 125000.0)
]
Each Employee.new(...) call creates an object with data (@name and @salary) and
behavior (change_salary and description)
employees.each do |emp|
emp.change_salary(10000.0)
end
•
employees.each do |emp|
emp.change_salary(10000.0)
end
We call the “change_salary” method we defined in our class, passing in a value
of 10000.0.
This adds our $10K to the employee’s salary and stores the sum in @salary,
overwriting the existing value
The description method to build our output string instead of trying to access the
data fields (@salary and @name) directly. This is called “data hiding” and it
allows us to change the names of our instance variables without forcing the
users of our object to change how they use it.
FP Approach
employees = [
[ "Bob", 100000.0 ],
[ "Jane", 125000.0 ]
]
Instead of converting the data to an object and then calling methods on it, we
write a pair of standalone methods called change_salaries (plural) and
change_salary (singular)
 we write a pair of standalone methods called change_salaries (plural) and
change_salary (singular). We pass change_salaries two arguments: the array
of arrays representing our data and the change amount. change_salaries
uses map instead of the each method we used in the OOP version
•
FP Approach
happier_employees = change_salaries(employees,
10000.0)
Because we don’t have objects, change_salaries requires that
we pass in not just the amount, but also the data we want to
modify.
FP Approach
happier_employees.each do |emp|
puts "#{emp[0]} makes #{emp[1]}"
end
Finally, we use ‘each’ to walk through every record in happier_employees and generate
the output message ourselves. This fits the FP model because FP likes to view
everything as a data transformation: you start with this dataset, apply these
transformations to it (in this case, adding $10K) and generate a new dataset
Another subtle -- but important -- difference is that in the OOP version change_salary
used each to process each employee, but the FP version uses map. Instead of
changing the original value, ’map’ creates a copy of the array containing the return value
of each pass. When all elements have been processed, map hands us the copy with all
the new values, which we store in happier_employees. The original array is untouched!
This idea of not changing the contents (or “state”) of a variable once it’s been created is
called immutability and is another key aspect of FP. Before and After state.

More Related Content

What's hot

DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019
Sabrina Marechal
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
Function
FunctionFunction
Function
Saniati
 
Java script function
Java script functionJava script function
Java script function
suresh raj sharma
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
Srajan Mor
 
Function overloading
Function overloadingFunction overloading
Function overloading
Ashish Kelwa
 
Function in c++
Function in c++Function in c++
Function in c++Kumar
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
Dr. C.V. Suresh Babu
 
Function
Function Function
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
Assaf Gannon
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
CSEC Mathematics Review - Introduction To Functions & Relations
CSEC Mathematics Review - Introduction To Functions & RelationsCSEC Mathematics Review - Introduction To Functions & Relations
CSEC Mathematics Review - Introduction To Functions & Relations
Kevin Small
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Abdullah Turkistani
 

What's hot (20)

Functions in python
Functions in python Functions in python
Functions in python
 
DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019DataWeave 2.0 - MuleSoft CONNECT 2019
DataWeave 2.0 - MuleSoft CONNECT 2019
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Function
FunctionFunction
Function
 
Java script function
Java script functionJava script function
Java script function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Python Built-in Functions and Use cases
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use cases
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function in c++
Function in c++Function in c++
Function in c++
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Create and analyse programs
Create and analyse programsCreate and analyse programs
Create and analyse programs
 
Function
Function Function
Function
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
CSEC Mathematics Review - Introduction To Functions & Relations
CSEC Mathematics Review - Introduction To Functions & RelationsCSEC Mathematics Review - Introduction To Functions & Relations
CSEC Mathematics Review - Introduction To Functions & Relations
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 

Similar to Basics of Functional Programming

Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
Edward D. Weinberger
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
TKSanthoshRao
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
tarunsharmaug23
 
Notes5
Notes5Notes5
Notes5hccit
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
NUST Stuff
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
Knoldus Inc.
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
abhi353063
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
jaba kumar
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
snowflakebatch
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
JuanPicasso7
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
Ashish Chamoli
 

Similar to Basics of Functional Programming (20)

Python functions
Python functionsPython functions
Python functions
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
Functional programming in python
Functional programming in pythonFunctional programming in python
Functional programming in python
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
 
Notes5
Notes5Notes5
Notes5
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
 
Handout # 3 functions c++
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
Introduction to Programming in LISP
Introduction to Programming in LISPIntroduction to Programming in LISP
Introduction to Programming in LISP
 
Functions
FunctionsFunctions
Functions
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
This first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docxThis first assignment will focus on coding in Python, applying kno.docx
This first assignment will focus on coding in Python, applying kno.docx
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
 
Arrays & functions in php
Arrays & functions in phpArrays & functions in php
Arrays & functions in php
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 

Basics of Functional Programming

  • 1. Functional Programming • Functional code is characterised by one thing: the absence of side effects. It doesn’t rely on data outside the current function, and it doesn’t change data that exists outside the current function. Every other “functional” thing can be derived from this property. Any examples of functions with side effects and no side effects? • The key to Functional Programming is in the name: functions. FP is about immutability and composing functions rather than objects.
  • 2. Functions are first class • What makes something first class?
  • 3. Functions are first class • What makes something first class? • It can be created on demand • It can be stored in a data structure • It can be passed as an argument to a function • It can be returned as the value of a function
  • 4. Creating functions on demand using composition Find the fifth element of a collection: (def fifth (comp first rest rest rest rest)) (fifth [1 2 3 4 5]) •comp : Takes a set of functions and returns a fn that is the composition of those fns •first: Returns the first item in the collection •rest: Returns a possibly empty seq of the items after the first. •Find nth element of a collection using composition?
  • 5. CREATING FUNCTIONS ON DEMAND USING PARTIAL FUNCTIONS ((partial + 5) 100 200) ;=> 305 The function partial builds a new function that partially applies the single argument 5 to the addition function. When the returned partial function is passed the arguments 100 and 200, the result is their summation plus that of the value 5 captured by partial. •
  • 6. USING FUNCTIONS AS DATA • First-class functions can not only be treated as data; they are data • It can be stored in a container expecting a piece of data, be it a local, a reference, collections, or anything able to store a java.lang.Object. (defn join {:test (fn [] (assert (= (join "," [1 2 3]) "1,3,3")))} [sep s] (apply str (interpose sep s))) •
  • 7. Higher-order functions A higher-order function is a function that does at least one of the following: • Takes one or more functions as arguments • Returns a function as a result
  • 8. Functions as Arguments (sort-by second [[:a 7], [:c 13], [:b 21]]) ;;=> ([:a 7] [:c 13] [:b 21])
  • 9. Functions as return values •(complement f) Takes a fn f and returns a fn that takes the same arguments as f, has the same effects, if any, and returns the opposite truth value. (def not-empty? (complement empty?)) ;; #'user/not-empty?
  • 10. Pure Functions Simply put, pure functions are regular functions that, through convention, conform to the following simple guidelines • The function always returns the same result, given the same arguments. • The function doesn’t cause any observable side effects.
  • 11. Pure or Impure? var x = 5; function addToX(a) { return a + x; } function getLength(array) { return array.length; } •
  • 12. Pure or Impure? function add(x, y) { return x + y; } function add(x,y) { updateDatabase(); return x + y; } •
  • 13. REFERENTIAL TRANSPARENCY TESTABILITY If a function is referentially transparent, then it’s easier to reason about and therefore more straightforward to test. Imagine the confusion should you add further impure functions based on further external transient values. OPTIMIZATION If a function is referentially transparent, then it can more easily be optimized using techniques such as memoization.
  • 14. OOPS vs FP Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods Functional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data
  • 15. OOP vs FP  the data (the stuff a program knows) the behaviors (the stuff a program can do to/with that data) •OOP says that bringing together data and its associated behavior in a single location (called an “object”) makes it easier to understand how a program works. •FP says that data and behavior are distinctively different things and should be kept separate for clarity.
  • 16. Let’s say you run a company and you’ve just decided to give all your employees a $10,000.00 raise. How could we write a command-line script to make this change?
  • 17. Approach using OOP class Employee def initialize(name, salary) @name = name @salary = salary end def change_salary(amt) @salary = @salary + amt end def description "#{@name} makes #{@salary}" end end •
  • 18. employees = [ Employee.new("Bob", 100000.0), Employee.new("Jane", 125000.0) ] Each Employee.new(...) call creates an object with data (@name and @salary) and behavior (change_salary and description) employees.each do |emp| emp.change_salary(10000.0) end •
  • 19. employees.each do |emp| emp.change_salary(10000.0) end We call the “change_salary” method we defined in our class, passing in a value of 10000.0. This adds our $10K to the employee’s salary and stores the sum in @salary, overwriting the existing value The description method to build our output string instead of trying to access the data fields (@salary and @name) directly. This is called “data hiding” and it allows us to change the names of our instance variables without forcing the users of our object to change how they use it.
  • 20. FP Approach employees = [ [ "Bob", 100000.0 ], [ "Jane", 125000.0 ] ] Instead of converting the data to an object and then calling methods on it, we write a pair of standalone methods called change_salaries (plural) and change_salary (singular)  we write a pair of standalone methods called change_salaries (plural) and change_salary (singular). We pass change_salaries two arguments: the array of arrays representing our data and the change amount. change_salaries uses map instead of the each method we used in the OOP version •
  • 21. FP Approach happier_employees = change_salaries(employees, 10000.0) Because we don’t have objects, change_salaries requires that we pass in not just the amount, but also the data we want to modify.
  • 22. FP Approach happier_employees.each do |emp| puts "#{emp[0]} makes #{emp[1]}" end Finally, we use ‘each’ to walk through every record in happier_employees and generate the output message ourselves. This fits the FP model because FP likes to view everything as a data transformation: you start with this dataset, apply these transformations to it (in this case, adding $10K) and generate a new dataset Another subtle -- but important -- difference is that in the OOP version change_salary used each to process each employee, but the FP version uses map. Instead of changing the original value, ’map’ creates a copy of the array containing the return value of each pass. When all elements have been processed, map hands us the copy with all the new values, which we store in happier_employees. The original array is untouched! This idea of not changing the contents (or “state”) of a variable once it’s been created is called immutability and is another key aspect of FP. Before and After state.