SlideShare a Scribd company logo
1 of 50
Download to read offline
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

"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them AllJohn De Goes
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional ArchitectureJohn De Goes
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!John De Goes
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and FutureJohn De Goes
 

What's hot (20)

"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
One Monad to Rule Them All
One Monad to Rule Them AllOne Monad to Rule Them All
One Monad to Rule Them All
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 

Viewers also liked

Os Peytonjones
Os PeytonjonesOs Peytonjones
Os Peytonjonesoscon2007
 
OCaml Labs introduction at OCaml Consortium 2012
OCaml Labs introduction at OCaml Consortium 2012OCaml Labs introduction at OCaml Consortium 2012
OCaml Labs introduction at OCaml Consortium 2012Anil Madhavapeddy
 
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlYamagata Yoriyuki
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Anil Madhavapeddy
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Anil Madhavapeddy
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellMichel Rijnders
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskellLuca Molteni
 
OCamlでWebアプリケーションを作るn個の方法
OCamlでWebアプリケーションを作るn個の方法OCamlでWebアプリケーションを作るn個の方法
OCamlでWebアプリケーションを作るn個の方法Hiroki Mizuno
 
Real World OCamlを読んでLispと協調してみた
Real World OCamlを読んでLispと協調してみたReal World OCamlを読んでLispと協調してみた
Real World OCamlを読んでLispと協調してみたblackenedgold
 
関数型プログラミング入門 with OCaml
関数型プログラミング入門 with OCaml関数型プログラミング入門 with OCaml
関数型プログラミング入門 with OCamlHaruka Oikawa
 
PythonistaがOCamlを実用する方法
PythonistaがOCamlを実用する方法PythonistaがOCamlを実用する方法
PythonistaがOCamlを実用する方法Yosuke Onoue
 
Neural Turing Machine Tutorial
Neural Turing Machine TutorialNeural Turing Machine Tutorial
Neural Turing Machine TutorialMark Chang
 
Haskell for the Real World
Haskell for the Real WorldHaskell for the Real World
Haskell for the Real WorldBryan O'Sullivan
 

Viewers also liked (19)

Os Peytonjones
Os PeytonjonesOs Peytonjones
Os Peytonjones
 
OCaml Labs introduction at OCaml Consortium 2012
OCaml Labs introduction at OCaml Consortium 2012OCaml Labs introduction at OCaml Consortium 2012
OCaml Labs introduction at OCaml Consortium 2012
 
Camomile : A Unicode library for OCaml
Camomile : A Unicode library for OCamlCamomile : A Unicode library for OCaml
Camomile : A Unicode library for OCaml
 
Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...Using functional programming within an industrial product group: perspectives...
Using functional programming within an industrial product group: perspectives...
 
Ocaml
OcamlOcaml
Ocaml
 
Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)Mirage: ML kernels in the cloud (ML Workshop 2010)
Mirage: ML kernels in the cloud (ML Workshop 2010)
 
Haskell - Functional Programming
Haskell - Functional ProgrammingHaskell - Functional Programming
Haskell - Functional Programming
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
計算数学
計算数学計算数学
計算数学
 
Lispmeetup11
Lispmeetup11Lispmeetup11
Lispmeetup11
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
OCamlでWebアプリケーションを作るn個の方法
OCamlでWebアプリケーションを作るn個の方法OCamlでWebアプリケーションを作るn個の方法
OCamlでWebアプリケーションを作るn個の方法
 
Real World OCamlを読んでLispと協調してみた
Real World OCamlを読んでLispと協調してみたReal World OCamlを読んでLispと協調してみた
Real World OCamlを読んでLispと協調してみた
 
関数型プログラミング入門 with OCaml
関数型プログラミング入門 with OCaml関数型プログラミング入門 with OCaml
関数型プログラミング入門 with OCaml
 
PythonistaがOCamlを実用する方法
PythonistaがOCamlを実用する方法PythonistaがOCamlを実用する方法
PythonistaがOCamlを実用する方法
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Neural Turing Machine Tutorial
Neural Turing Machine TutorialNeural Turing Machine Tutorial
Neural Turing Machine Tutorial
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Haskell for the Real World
Haskell for the Real WorldHaskell for the Real World
Haskell for the Real World
 

Similar to A taste of Functional Programming

Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdfPuneetChaturvedi23
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programmingkenbot
 
Truth, deduction, computation lecture f
Truth, deduction, computation   lecture fTruth, deduction, computation   lecture f
Truth, deduction, computation lecture fVlad Patryshev
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software DevelopmentNaveenkumar Muguda
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkDB Tsai
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technicalalpinedatalabs
 

Similar to A taste of Functional Programming (20)

Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Scala qq
Scala qqScala qq
Scala qq
 
Functional go
Functional goFunctional go
Functional go
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
 
Truth, deduction, computation lecture f
Truth, deduction, computation   lecture fTruth, deduction, computation   lecture f
Truth, deduction, computation lecture f
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache Spark
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technical
 

More from Jordan Open Source Association

JOSA TechTalks - Machine Learning on Graph-Structured Data
JOSA TechTalks - Machine Learning on Graph-Structured DataJOSA TechTalks - Machine Learning on Graph-Structured Data
JOSA TechTalks - Machine Learning on Graph-Structured DataJordan Open Source Association
 
JOSA TechTalks - Word Embedding and Word2Vec Explained
JOSA TechTalks - Word Embedding and Word2Vec ExplainedJOSA TechTalks - Word Embedding and Word2Vec Explained
JOSA TechTalks - Word Embedding and Word2Vec ExplainedJordan Open Source Association
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJordan Open Source Association
 

More from Jordan Open Source Association (20)

JOSA TechTalks - Data Oriented Architecture
JOSA TechTalks - Data Oriented ArchitectureJOSA TechTalks - Data Oriented Architecture
JOSA TechTalks - Data Oriented Architecture
 
JOSA TechTalks - Machine Learning on Graph-Structured Data
JOSA TechTalks - Machine Learning on Graph-Structured DataJOSA TechTalks - Machine Learning on Graph-Structured Data
JOSA TechTalks - Machine Learning on Graph-Structured Data
 
OpenSooq Mobile Infrastructure @ Scale
OpenSooq Mobile Infrastructure @ ScaleOpenSooq Mobile Infrastructure @ Scale
OpenSooq Mobile Infrastructure @ Scale
 
Data-Driven Digital Transformation
Data-Driven Digital TransformationData-Driven Digital Transformation
Data-Driven Digital Transformation
 
Data Science in Action
Data Science in ActionData Science in Action
Data Science in Action
 
Processing Arabic Text
Processing Arabic TextProcessing Arabic Text
Processing Arabic Text
 
JOSA TechTalks - Downgrade your Costs
JOSA TechTalks - Downgrade your CostsJOSA TechTalks - Downgrade your Costs
JOSA TechTalks - Downgrade your Costs
 
JOSA TechTalks - Docker in Production
JOSA TechTalks - Docker in ProductionJOSA TechTalks - Docker in Production
JOSA TechTalks - Docker in Production
 
JOSA TechTalks - Word Embedding and Word2Vec Explained
JOSA TechTalks - Word Embedding and Word2Vec ExplainedJOSA TechTalks - Word Embedding and Word2Vec Explained
JOSA TechTalks - Word Embedding and Word2Vec Explained
 
JOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and ReduxJOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and Redux
 
JOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best PracticesJOSA TechTalks - RESTful API Concepts and Best Practices
JOSA TechTalks - RESTful API Concepts and Best Practices
 
Web app architecture
Web app architectureWeb app architecture
Web app architecture
 
Intro to the Principles of Graphic Design
Intro to the Principles of Graphic DesignIntro to the Principles of Graphic Design
Intro to the Principles of Graphic Design
 
Intro to Graphic Design Elements
Intro to Graphic Design ElementsIntro to Graphic Design Elements
Intro to Graphic Design Elements
 
JOSA TechTalk: Realtime monitoring and alerts
JOSA TechTalk: Realtime monitoring and alerts JOSA TechTalk: Realtime monitoring and alerts
JOSA TechTalk: Realtime monitoring and alerts
 
JOSA TechTalk: Metadata Management
in Big Data
JOSA TechTalk: Metadata Management
in Big DataJOSA TechTalk: Metadata Management
in Big Data
JOSA TechTalk: Metadata Management
in Big Data
 
JOSA TechTalk: Introduction to Supervised Learning
JOSA TechTalk: Introduction to Supervised LearningJOSA TechTalk: Introduction to Supervised Learning
JOSA TechTalk: Introduction to Supervised Learning
 
JOSA TechTalk: Taking Docker to Production
JOSA TechTalk: Taking Docker to ProductionJOSA TechTalk: Taking Docker to Production
JOSA TechTalk: Taking Docker to Production
 
JOSA TechTalk: Introduction to docker
JOSA TechTalk: Introduction to dockerJOSA TechTalk: Introduction to docker
JOSA TechTalk: Introduction to docker
 
D programming language
D programming languageD programming language
D programming language
 

Recently uploaded

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Recently uploaded (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

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