SlideShare a Scribd company logo
A Taste of Functional
Programming with Haskell
Mohammad Ghabboun Functional→
Programming
Functional Programming
Languages
● Haskell
● Standard ML
● OCaml
● Scheme
● Clojure
● F#
● Scala
● Erlange
What is a Function ?
What is a function?
● Functions that fail (Null, exceptions...)
● Functions that go into infinite loop
● Functions that do IO
● Function that have side effects (change state)
● ...
What is a function?
● Functions that fail (Null, exceptions...)
● Functions that go into infinite loop
● Functions that do IO
● Function that have side effects (change state)
● Those are not functions but actually procedures
● So...
What is a function ?
X
Y
Shape Color
What is a function ?
Pure functions in Haskell, as math functions,
is mapping between two values
int add ( int x, int y )
{
return x + y;
}
Add :: Int → Int → Int
Add x y = x + y
No assignments, only equality!
● Let x = 4
● x = 6 (error!)
● x is 4 it cannot be changed
● Left equals Right
● Let y = 5
● y = y + 1 (error!)
● (y-y) = 1
● 0 = 1 wrong!!
The Essence of Composition
INPUT x
FUNCTION f:
OUTPUT f(x)
INPUT x
FUNCTION f:
OUTPUT f(x)
- All dependencies are
explicit
- No side effects
- Easier to reason
about
- Same output for the
same input every
time
What is Functional
Programming (FP) ?
FP is about focusing on the
solution
It's about computing results and not
performing actions..
Motivational Example
bool isPrime(int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (unsigned int i = 2; i < n; ++i)
if (n % i == 0)
return false;
return true;
}
Imperative Programming
● Inspired by Von nueman machine
● Values occupy memory
● Statements (steps)
● State mutation
● Control structures
● (if, for, break, return..)
Arithmetic
Logic
Unit
Control
Unit
Memory
Input Output
Accumulator
Motivational Example
● isPrime :: Int → Bool
● isPrime n = not (any (divides n) [2..n-1])
● A prime number is a natural number greater than 1 that has no
positive divisors other than 1 and itself. - wikipedia
Functional Programming (Haskell)
● Haskell is the purest FP language
● General purpose
● Functions as first class values
● Strongly Typed
● Based on Lambda Calculus and Category
Theory
Real World Applications of FP
● Haxl Project (Facebook)
● Financial Applications (Standard Chartered )
● Algebird Library for Big Data Patterns (e.g.
Map, Reduce, Monoids, Monads )
● Compilers (Perl Compiler and many DSLs)
● Static Analysis (Galois)
Quick, Sort, Example
● sort [] = []
● sort (x:xs) = sort (filter (<x) xs) ++ [x] ++
sort (filter (>=x) xs)
FP Is Building Higher Level
Abstractions
Less boilerplate code Less bugs→
There is a pattern hiding
somewhere...
int Sum ( array<int> v )
{
int sum = 0;
for (int i = 0; i < v.size(); ++i )
{
sum += v[i];
}
return sum;
}
How can we transform it into pure
function ?
int Sum ( array<int> v )
{
int sum = 0;
for (int i = 0; i < v.size(); ++i )
{
sum += v[i];
}
return sum;
}
Recursion ?
int Sum ( vector<int> v, int i )
{
if ( i >= v.size())
return 0;
return v[i] + Sum ( v, i+1 );
}
Recursion ?
int Sum ( vector<int> v, int i )
{
if ( i >= v.size())
return 0;
return v[i] + Sum ( v, i+1 );
}
sum :: [Int] → Int
sum [] = 0
sum (head:rest) = head + sum rest
Recursion ?
sum :: [Int] → Int
sum [] = 0
sum (x:xs) = x + sum xs
Recursion ?
sum :: [Int] → Int
sum [] = 0
sum (x:xs) = x + sum xs
product :: [Int] → Int
product [] = 0
product (x:xs) = x * product xs
Higher Order Functions
fold :: [Int] → Int
fold [] = 0
fold (x:xs) = x + fold xs
Higher Order Functions
fold :: [Int] → Int
fold [] = 0
fold (x:xs) = x + fold xs
fold :: (b → a → b) → b → [a] → b
fold f acc [] = acc
fold f acc (x:xs) = f acc (fold f x xs)
We just introduced a universal
operator
● sum :: [Int] → Int
● sum = foldl (+) 0
● product :: [Int] → Int
● product = foldl (*) 1
● length :: [Int] → Int
● length = foldl (x → x+1) []
Quick Look at Maps
● Maps are very popular operator in programming languages and
especially functional languages
● It applies a function on every element of a list
● map (x → x*2) [0,1,2,3,4,5]
● [0,2,4,6,8,10]
Quick Look at Maps
● map :: (a → b) → [a] → [b]
● map _ [] = []
● map f (x:xs) = f x : map f xs
● Do you recognize this pattern ?
Quick Look at Maps
● map :: (a → b) → [a] → [b]
● map _ [] = []
● map f (x:xs) = f x : map f xs
● Do you recognize this pattern ?
● It turns out this is a Fold pattern
● map f = foldl (x xs → f x : xs) []
FP Is about Controlling Effects
Everytime I see a Null I kill a cat
-Anonymous
“Null is the billion dollar mistake”
-Tony Hoare
J language example
● class HashMap {
public V get ( Object key );
}
J language example
● class HashMap {
public V get ( Object key );
}
● Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
J language example
● class HashMap {
public V get ( Object key );
}
● Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
● More formally, if this map contains a mapping from a key k to a
value v such that (key==null ? k==null : key.equals(k)), then this
method returns v; otherwise it returns null. (There can be at most
one such mapping.)
● A return value of null does not necessarily indicate that the map
contains no mapping for the key; it's also possible that the map
explicitly maps the key to null. The containsKey operation may be
used to distinguish these two cases.
How to capture effects ?
● If all we have is pure function
● Type Type→
● How can we capture effects..
– Failure?
– Returning multiple values?
– IO ??
– States ???
Capturing Effects
● lookup :: a -> [(a, b)] -> b
●
But this function can't capture failure if a was not in the dictionary
● Let's solve this problem...
Algebraic Data Types
● But First...
● Let's define some data types
● data Bool = True | False
● data Point = (Float,Float)
Algebraic Data Types
● But First...
● Let's define some data types
● data Bool = True | False
● data Point = (Float,Float)
● Let's introduce a type that capture failures
● data Maybe a = Nothing | Just a
Capturing Effects
● lookup :: a -> [(a, b)] -> Maybe b
● Now failure is captured by type
● Your code have to check for failure
● Failure is explicit
● Problem solved...
Computational Context
Int
MaybeMaybe
IntInt
Only capture values
Captures failure
Computational Context
Int
ListList
IntInt
Only capture values
Capture Collections
and Non-determinism
Computational Context
Int
IOIO
IntInt
Only capture values
Capture Actions
Map and Lifting
● There is more to map than meets the eye..
● map (x → x*x) [1,2,3,4]
● [1,4,9,16]
● map :: (a → b) → [a] → [b]
● map :: (a → b) → ([a] → [b])
Map Generalization
● Map took a function that works on Int
● returned a function that works on [Int]
● map :: (a → b) → ([a] → [b])
● fmap :: (a → b) → (t a → t b)
Map Generalization
● Map took a function that works on Int
● returned a function that works on T<Int>
● map :: (a → b) → ([a] → [b])
● fmap :: (a → b) → (t a → t b)
● So what is this t we are talking about ?
● t is any computational context we talked about
(Maybe, IO, Lists)
What we have so far..
● A data type, that takes a type and returns another
● Maybe takes Int → Maybe Int
● It's also called a type constructor
● A function that takes a function and returns a lifted function
● fmap :: (a → b) → (t a → t b)
● Any data type that have those two properties is called Functor
Solving Real Problems With Lifting
array< pair<int,int> > CartesianProduct ( array<int> a,
array<int> b )
{
array result;
for (int i=0; i < a.size(); ++i)
{
for (int j=0; j < b.size(); ++j)
{
result.add( make_pair(a[i],b[j]) );
}
}
return result;
}
Solving Real Problems With Functors
● (,) :: a -> b -> (a,b)
● We want to apply it on lists..
● We can lift it to work on lists
● let lifterPair = fmap (,) [1,2,3,4]
● :t lifterPair :: [b -> (Integer, b)]
● lifterPair <*> [5,6,7,8]
Solving Real Problems With Functors
● Even better
● cartProd :: [a] -> [b] -> [(a, b)]
● cartProd = liftA2 (,)
Conclusion
● FP is about focusing on the problems
● FP is about higher level abstractions
● FP is about reducing bugs
● FP is about precise thinking

More Related Content

What's hot (20)

PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
ODP
Clojure basics
Knoldus Inc.
 
PDF
Hey! There's OCaml in my Rust!
Kel Cecil
 
PPT
friends functionToshu
Sidd Singh
 
PDF
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
PDF
Scala categorytheory
Knoldus Inc.
 
PDF
Procedural Programming: It’s Back? It Never Went Away
Kevlin Henney
 
PDF
Functional Programming Patterns for the Pragmatic Programmer
Raúl Raja Martínez
 
PDF
One Monad to Rule Them All
John De Goes
 
PPTX
Functional programming in JavaScript
Joseph Smith
 
PDF
Orthogonal Functional Architecture
John De Goes
 
PDF
First-Class Patterns
John De Goes
 
PDF
All Aboard The Scala-to-PureScript Express!
John De Goes
 
PDF
MTL Versus Free
John De Goes
 
PDF
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
PDF
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
PDF
Haskell for data science
John Cant
 
PDF
Kotlin, why?
Paweł Byszewski
 
PDF
Refactoring to Immutability
Kevlin Henney
 
PDF
Halogen: Past, Present, and Future
John De Goes
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
Clojure basics
Knoldus Inc.
 
Hey! There's OCaml in my Rust!
Kel Cecil
 
friends functionToshu
Sidd Singh
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
John De Goes
 
Scala categorytheory
Knoldus Inc.
 
Procedural Programming: It’s Back? It Never Went Away
Kevlin Henney
 
Functional Programming Patterns for the Pragmatic Programmer
Raúl Raja Martínez
 
One Monad to Rule Them All
John De Goes
 
Functional programming in JavaScript
Joseph Smith
 
Orthogonal Functional Architecture
John De Goes
 
First-Class Patterns
John De Goes
 
All Aboard The Scala-to-PureScript Express!
John De Goes
 
MTL Versus Free
John De Goes
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Haskell for data science
John Cant
 
Kotlin, why?
Paweł Byszewski
 
Refactoring to Immutability
Kevlin Henney
 
Halogen: Past, Present, and Future
John De Goes
 

Viewers also liked (19)

PDF
Os Peytonjones
oscon2007
 
PDF
OCaml Labs introduction at OCaml Consortium 2012
Anil Madhavapeddy
 
PDF
Camomile : A Unicode library for OCaml
Yamagata Yoriyuki
 
PPTX
Using functional programming within an industrial product group: perspectives...
Anil Madhavapeddy
 
PPT
Mirage: ML kernels in the cloud (ML Workshop 2010)
Anil Madhavapeddy
 
PDF
Haskell - Functional Programming
Giovane Berny Possebon
 
KEY
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
ODP
計算数学
blackenedgold
 
ODP
Lispmeetup11
blackenedgold
 
PDF
Introduction to haskell
Luca Molteni
 
PDF
OCamlでWebアプリケーションを作るn個の方法
Hiroki Mizuno
 
ODP
Real World OCamlを読んでLispと協調してみた
blackenedgold
 
PDF
関数型プログラミング入門 with OCaml
Haruka Oikawa
 
PDF
PythonistaがOCamlを実用する方法
Yosuke Onoue
 
PDF
Why Haskell
Susan Potter
 
PPTX
Neural Turing Machine Tutorial
Mark Chang
 
PDF
Object-oriented Basics
Jamie (Taka) Wang
 
PDF
Haskell for the Real World
Bryan O'Sullivan
 
Os Peytonjones
oscon2007
 
OCaml Labs introduction at OCaml Consortium 2012
Anil Madhavapeddy
 
Camomile : A Unicode library for OCaml
Yamagata Yoriyuki
 
Using functional programming within an industrial product group: perspectives...
Anil Madhavapeddy
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Anil Madhavapeddy
 
Haskell - Functional Programming
Giovane Berny Possebon
 
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
計算数学
blackenedgold
 
Lispmeetup11
blackenedgold
 
Introduction to haskell
Luca Molteni
 
OCamlでWebアプリケーションを作るn個の方法
Hiroki Mizuno
 
Real World OCamlを読んでLispと協調してみた
blackenedgold
 
関数型プログラミング入門 with OCaml
Haruka Oikawa
 
PythonistaがOCamlを実用する方法
Yosuke Onoue
 
Why Haskell
Susan Potter
 
Neural Turing Machine Tutorial
Mark Chang
 
Object-oriented Basics
Jamie (Taka) Wang
 
Haskell for the Real World
Bryan O'Sullivan
 
Ad

Similar to A taste of Functional Programming (20)

PDF
Functional programming with haskell
faradjpour
 
PPTX
The joy of functional programming
Steve Zhang
 
PDF
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
 
PPTX
Good functional programming is good programming
kenbot
 
PDF
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
PPTX
Functional programming for the Advanced Beginner
Luis Atencio
 
PDF
Functional programming ii
Prashant Kalkar
 
PDF
Why Haskell Matters
romanandreg
 
PPS
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
PDF
Scala. Introduction to FP. Monads
Kirill Kozlov
 
PDF
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
PDF
FSharp Talk
HaiBin Chang
 
PDF
10. haskell Modules
Sebastian Rettig
 
PDF
Functional programming from its fundamentals
Mauro Palsgraaf
 
PDF
The Fuss about || Haskell | Scala | F# ||
Ashwin Rao
 
PDF
Functional programming-advantages
Sergei Winitzki
 
PDF
Monad presentation scala as a category
samthemonad
 
PDF
Making the most of lambdas
Robert Zych
 
PDF
The Next Great Functional Programming Language
John De Goes
 
PDF
Introduction to Functional Languages
suthi
 
Functional programming with haskell
faradjpour
 
The joy of functional programming
Steve Zhang
 
Rainer Grimm, “Functional Programming in C++11”
Platonov Sergey
 
Good functional programming is good programming
kenbot
 
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Functional programming for the Advanced Beginner
Luis Atencio
 
Functional programming ii
Prashant Kalkar
 
Why Haskell Matters
romanandreg
 
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Go Beyond Higher Order Functions: A Journey into Functional Programming
Lex Sheehan
 
FSharp Talk
HaiBin Chang
 
10. haskell Modules
Sebastian Rettig
 
Functional programming from its fundamentals
Mauro Palsgraaf
 
The Fuss about || Haskell | Scala | F# ||
Ashwin Rao
 
Functional programming-advantages
Sergei Winitzki
 
Monad presentation scala as a category
samthemonad
 
Making the most of lambdas
Robert Zych
 
The Next Great Functional Programming Language
John De Goes
 
Introduction to Functional Languages
suthi
 
Ad

More from Jordan Open Source Association (20)

PPTX
JOSA TechTalks - Data Oriented Architecture
Jordan Open Source Association
 
PPTX
JOSA TechTalks - Machine Learning on Graph-Structured Data
Jordan Open Source Association
 
PDF
OpenSooq Mobile Infrastructure @ Scale
Jordan Open Source Association
 
PDF
Data-Driven Digital Transformation
Jordan Open Source Association
 
PDF
Data Science in Action
Jordan Open Source Association
 
PDF
Processing Arabic Text
Jordan Open Source Association
 
PDF
JOSA TechTalks - Downgrade your Costs
Jordan Open Source Association
 
PDF
JOSA TechTalks - Docker in Production
Jordan Open Source Association
 
PPTX
JOSA TechTalks - Word Embedding and Word2Vec Explained
Jordan Open Source Association
 
PDF
JOSA TechTalks - Better Web Apps with React and Redux
Jordan Open Source Association
 
PDF
JOSA TechTalks - RESTful API Concepts and Best Practices
Jordan Open Source Association
 
PDF
Web app architecture
Jordan Open Source Association
 
PDF
Intro to the Principles of Graphic Design
Jordan Open Source Association
 
ODP
Intro to Graphic Design Elements
Jordan Open Source Association
 
PDF
JOSA TechTalk: Realtime monitoring and alerts
Jordan Open Source Association
 
PPTX
JOSA TechTalk: Metadata Management
in Big Data
Jordan Open Source Association
 
ODP
JOSA TechTalk: Introduction to Supervised Learning
Jordan Open Source Association
 
PDF
JOSA TechTalk: Taking Docker to Production
Jordan Open Source Association
 
PDF
JOSA TechTalk: Introduction to docker
Jordan Open Source Association
 
PDF
D programming language
Jordan Open Source Association
 
JOSA TechTalks - Data Oriented Architecture
Jordan Open Source Association
 
JOSA TechTalks - Machine Learning on Graph-Structured Data
Jordan Open Source Association
 
OpenSooq Mobile Infrastructure @ Scale
Jordan Open Source Association
 
Data-Driven Digital Transformation
Jordan Open Source Association
 
Data Science in Action
Jordan Open Source Association
 
Processing Arabic Text
Jordan Open Source Association
 
JOSA TechTalks - Downgrade your Costs
Jordan Open Source Association
 
JOSA TechTalks - Docker in Production
Jordan Open Source Association
 
JOSA TechTalks - Word Embedding and Word2Vec Explained
Jordan Open Source Association
 
JOSA TechTalks - Better Web Apps with React and Redux
Jordan Open Source Association
 
JOSA TechTalks - RESTful API Concepts and Best Practices
Jordan Open Source Association
 
Web app architecture
Jordan Open Source Association
 
Intro to the Principles of Graphic Design
Jordan Open Source Association
 
Intro to Graphic Design Elements
Jordan Open Source Association
 
JOSA TechTalk: Realtime monitoring and alerts
Jordan Open Source Association
 
JOSA TechTalk: Metadata Management
in Big Data
Jordan Open Source Association
 
JOSA TechTalk: Introduction to Supervised Learning
Jordan Open Source Association
 
JOSA TechTalk: Taking Docker to Production
Jordan Open Source Association
 
JOSA TechTalk: Introduction to docker
Jordan Open Source Association
 
D programming language
Jordan Open Source Association
 

Recently uploaded (20)

PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 

A taste of Functional Programming

  • 1. A Taste of Functional Programming with Haskell Mohammad Ghabboun Functional→ Programming
  • 2. Functional Programming Languages ● Haskell ● Standard ML ● OCaml ● Scheme ● Clojure ● F# ● Scala ● Erlange
  • 3. What is a Function ?
  • 4. What is a function? ● Functions that fail (Null, exceptions...) ● Functions that go into infinite loop ● Functions that do IO ● Function that have side effects (change state) ● ...
  • 5. What is a function? ● Functions that fail (Null, exceptions...) ● Functions that go into infinite loop ● Functions that do IO ● Function that have side effects (change state) ● Those are not functions but actually procedures ● So...
  • 6. What is a function ? X Y Shape Color
  • 7. What is a function ? Pure functions in Haskell, as math functions, is mapping between two values int add ( int x, int y ) { return x + y; } Add :: Int → Int → Int Add x y = x + y
  • 8. No assignments, only equality! ● Let x = 4 ● x = 6 (error!) ● x is 4 it cannot be changed ● Left equals Right ● Let y = 5 ● y = y + 1 (error!) ● (y-y) = 1 ● 0 = 1 wrong!!
  • 9. The Essence of Composition INPUT x FUNCTION f: OUTPUT f(x) INPUT x FUNCTION f: OUTPUT f(x) - All dependencies are explicit - No side effects - Easier to reason about - Same output for the same input every time
  • 11. FP is about focusing on the solution It's about computing results and not performing actions..
  • 12. Motivational Example bool isPrime(int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i < n; ++i) if (n % i == 0) return false; return true; }
  • 13. Imperative Programming ● Inspired by Von nueman machine ● Values occupy memory ● Statements (steps) ● State mutation ● Control structures ● (if, for, break, return..) Arithmetic Logic Unit Control Unit Memory Input Output Accumulator
  • 14. Motivational Example ● isPrime :: Int → Bool ● isPrime n = not (any (divides n) [2..n-1]) ● A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. - wikipedia
  • 15. Functional Programming (Haskell) ● Haskell is the purest FP language ● General purpose ● Functions as first class values ● Strongly Typed ● Based on Lambda Calculus and Category Theory
  • 16. Real World Applications of FP ● Haxl Project (Facebook) ● Financial Applications (Standard Chartered ) ● Algebird Library for Big Data Patterns (e.g. Map, Reduce, Monoids, Monads ) ● Compilers (Perl Compiler and many DSLs) ● Static Analysis (Galois)
  • 17. Quick, Sort, Example ● sort [] = [] ● sort (x:xs) = sort (filter (<x) xs) ++ [x] ++ sort (filter (>=x) xs)
  • 18. FP Is Building Higher Level Abstractions Less boilerplate code Less bugs→
  • 19. There is a pattern hiding somewhere... int Sum ( array<int> v ) { int sum = 0; for (int i = 0; i < v.size(); ++i ) { sum += v[i]; } return sum; }
  • 20. How can we transform it into pure function ? int Sum ( array<int> v ) { int sum = 0; for (int i = 0; i < v.size(); ++i ) { sum += v[i]; } return sum; }
  • 21. Recursion ? int Sum ( vector<int> v, int i ) { if ( i >= v.size()) return 0; return v[i] + Sum ( v, i+1 ); }
  • 22. Recursion ? int Sum ( vector<int> v, int i ) { if ( i >= v.size()) return 0; return v[i] + Sum ( v, i+1 ); } sum :: [Int] → Int sum [] = 0 sum (head:rest) = head + sum rest
  • 23. Recursion ? sum :: [Int] → Int sum [] = 0 sum (x:xs) = x + sum xs
  • 24. Recursion ? sum :: [Int] → Int sum [] = 0 sum (x:xs) = x + sum xs product :: [Int] → Int product [] = 0 product (x:xs) = x * product xs
  • 25. Higher Order Functions fold :: [Int] → Int fold [] = 0 fold (x:xs) = x + fold xs
  • 26. Higher Order Functions fold :: [Int] → Int fold [] = 0 fold (x:xs) = x + fold xs fold :: (b → a → b) → b → [a] → b fold f acc [] = acc fold f acc (x:xs) = f acc (fold f x xs)
  • 27. We just introduced a universal operator ● sum :: [Int] → Int ● sum = foldl (+) 0 ● product :: [Int] → Int ● product = foldl (*) 1 ● length :: [Int] → Int ● length = foldl (x → x+1) []
  • 28. Quick Look at Maps ● Maps are very popular operator in programming languages and especially functional languages ● It applies a function on every element of a list ● map (x → x*2) [0,1,2,3,4,5] ● [0,2,4,6,8,10]
  • 29. Quick Look at Maps ● map :: (a → b) → [a] → [b] ● map _ [] = [] ● map f (x:xs) = f x : map f xs ● Do you recognize this pattern ?
  • 30. Quick Look at Maps ● map :: (a → b) → [a] → [b] ● map _ [] = [] ● map f (x:xs) = f x : map f xs ● Do you recognize this pattern ? ● It turns out this is a Fold pattern ● map f = foldl (x xs → f x : xs) []
  • 31. FP Is about Controlling Effects Everytime I see a Null I kill a cat -Anonymous “Null is the billion dollar mistake” -Tony Hoare
  • 32. J language example ● class HashMap { public V get ( Object key ); }
  • 33. J language example ● class HashMap { public V get ( Object key ); } ● Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • 34. J language example ● class HashMap { public V get ( Object key ); } ● Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. ● More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.) ● A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
  • 35. How to capture effects ? ● If all we have is pure function ● Type Type→ ● How can we capture effects.. – Failure? – Returning multiple values? – IO ?? – States ???
  • 36. Capturing Effects ● lookup :: a -> [(a, b)] -> b ● But this function can't capture failure if a was not in the dictionary ● Let's solve this problem...
  • 37. Algebraic Data Types ● But First... ● Let's define some data types ● data Bool = True | False ● data Point = (Float,Float)
  • 38. Algebraic Data Types ● But First... ● Let's define some data types ● data Bool = True | False ● data Point = (Float,Float) ● Let's introduce a type that capture failures ● data Maybe a = Nothing | Just a
  • 39. Capturing Effects ● lookup :: a -> [(a, b)] -> Maybe b ● Now failure is captured by type ● Your code have to check for failure ● Failure is explicit ● Problem solved...
  • 41. Computational Context Int ListList IntInt Only capture values Capture Collections and Non-determinism
  • 43. Map and Lifting ● There is more to map than meets the eye.. ● map (x → x*x) [1,2,3,4] ● [1,4,9,16] ● map :: (a → b) → [a] → [b] ● map :: (a → b) → ([a] → [b])
  • 44. Map Generalization ● Map took a function that works on Int ● returned a function that works on [Int] ● map :: (a → b) → ([a] → [b]) ● fmap :: (a → b) → (t a → t b)
  • 45. Map Generalization ● Map took a function that works on Int ● returned a function that works on T<Int> ● map :: (a → b) → ([a] → [b]) ● fmap :: (a → b) → (t a → t b) ● So what is this t we are talking about ? ● t is any computational context we talked about (Maybe, IO, Lists)
  • 46. What we have so far.. ● A data type, that takes a type and returns another ● Maybe takes Int → Maybe Int ● It's also called a type constructor ● A function that takes a function and returns a lifted function ● fmap :: (a → b) → (t a → t b) ● Any data type that have those two properties is called Functor
  • 47. Solving Real Problems With Lifting array< pair<int,int> > CartesianProduct ( array<int> a, array<int> b ) { array result; for (int i=0; i < a.size(); ++i) { for (int j=0; j < b.size(); ++j) { result.add( make_pair(a[i],b[j]) ); } } return result; }
  • 48. Solving Real Problems With Functors ● (,) :: a -> b -> (a,b) ● We want to apply it on lists.. ● We can lift it to work on lists ● let lifterPair = fmap (,) [1,2,3,4] ● :t lifterPair :: [b -> (Integer, b)] ● lifterPair <*> [5,6,7,8]
  • 49. Solving Real Problems With Functors ● Even better ● cartProd :: [a] -> [b] -> [(a, b)] ● cartProd = liftA2 (,)
  • 50. Conclusion ● FP is about focusing on the problems ● FP is about higher level abstractions ● FP is about reducing bugs ● FP is about precise thinking