SlideShare a Scribd company logo
Functional
Programming
with Haskell
Adriano Bonat
abonat@thoughtworks.com
@tanob
Why FP?
• Source of new ideas
• Expressiveness
• Multi-core CPUs
• Different paradigm
New ideas:
Garbage collection (LISP)
Type inference (simply
typed lambda calculus)
Generics
Type classes
Expressiveness:
DSLs
What is it?
• Different programming paradigm
• OO
• Logic
• Procedural
• Functions are the main element in the
language
Function applications
“Functional programming is so called because a
program consists entirely of functions. [...]
Typically the main function is defined in terms of other
functions, which in turn are defined in terms of still
more functions, until at the bottom level the functions
are language primitives.”
John Hughes, 1989 -Why functional programming matters
Origin
Alonzo Church developed Lambda
Calculus as part of his
investigations on Math foundations
on 1936.
Lambda Calculus
• Variables
• Expressions (e1 e2)
• Lambda abstractions (λx. e)
Lambda Calculus (I)
• true = λxy. x
• false = λxy. y
• NOT a = (a)(false)(true)
• a AND b = (a)(b)(false)
• a OR b = (a)(true)(b)
• a XOR b = (a)((b)(false)(true))(b)
Haskell
• Academic origin
• Named in honor of Haskell Curry
• Defined by a committee
• First version released on 98 (Haskell 98)
Features
• Pureness
• Type Inference
• Algebraic datatypes (ADTs)
• Pattern Matching
• Lazyness
• High Order Functions
• Currification (aka Partial Application)
• Type Classes
• Monads
Pureness
• No side-effects
• A function call can have no effect other
than to compute its result
• Expressions can be evaluated at any time
• Programs are “referentially transparent”
Good for:
* reasoning
* compiler optimization
* concurrency
Type Inference
Let’s see the types for these declarations:
four = 4
add x y = x + y
emphasize x = x ++ “!”
Algebraic datatypes
Enumeration:
data Season = Summer | Winter | Autumn | Spring
Product:
data Pair = Pair Int Int
Sum:
data Shape = Circle Float | Rect Float Float
Polymorfic & Recursive:
data Tree a = Leaf a | Node (Tree a) (Tree a)
Algebraic datatypes (I)
data Maybe a = Nothing | Just a
data Either a b = Left a | Right b
Pattern Matching
Definition:
sum [] = 0
sum (elem:rest) = elem + sum rest
Application:
sum [1,2,3,10]
Pattern Matching (I)
area (Circle rad) = pi * rad ^ 2
area (Rect width height) = width * height
first (Pair value _) = value
High Order Functions
Functions which at least:
• Receive functions as parameters
• Return functions (aka curried functions)
High Order Functions (I)
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
Currification
add :: Int -> Int -> Int
add x y = x + y
inc :: Int -> Int
inc = add 1
Lazyness
• aka “call by need”
• Expressions can be evaluated when
necessary
• Allows the use of infinite lists
Being pure helps here
Lazyness (I)
Definition:
even_numbers :: [Int]
even_numbers = filter even [1..]
Application:
take 5 even_numbers
Lazyness (II)
fibs :: [Int]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
From: http://en.wikipedia.org/wiki/Lazy_evaluation
Type Classes
• Created to solve the problem with numeric
operator overload and equality testing
• Some type classes defined by Haskell 98:
• Eq
• Read/Show
Type Classes (I)
class Eq a where
(==), (/=) :: a -> a -> Bool
x == y = not (x /= y)
x /= y = not (x == y) You can define what is
called a “minimal
implementation”.
Type Classes (II)
data User = User { name :: String }
instance Eq User where
user1 == user2 = name user1 == name user2
instance Show User where
show user = name user
Automatic Derivation
data Season = Summer | Winter | Autumn | Spring
deriving (Show, Eq)
show Summer
> “Summer”
Summer /=Winter
> True
Monads
• Adds to the type system a way to describe
actions
• The actions will happen in a certain order
Monads
• Common monads:
• IO
• State
• Reader
• Maybe
Monads
thing1 >>= x ->
func1 x >>= y ->
thing2 >>= _ ->
func2 y >>= z ->
return z
do
x <- thing1
y <- func1 x
thing2
z <- func2 y
return z
sugar no-sugar
Monads
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
“return” is a bad name, it
actually injects a value
into the monadic type.
Logger Monad
type Log = [String]
data Logger resultType = Logger (resultType, Log)
deriving Show
record x = Logger ((), [x])
instance Monad Logger where
return value = Logger (value, [])
prevLogger >>= nextAction =
let Logger (prevResult, prevLog) = prevLogger
Logger (newResult, newLog) = nextAction prevResult
in Logger (newResult, prevLog ++ newLog)
Testing?
• Go read about QuickCheck!
Want to learn more?
Freely available online:
http://book.realworldhaskell.org/
Your Knowledge Portfolio
"Learn at least one new language every year.
[...] Different languages solve the same
problems in different ways. By learning several
different approaches, you can help broaden
your thinking and avoid getting stuck in a
rut."
The Pragmatic Programmer
Functional
Programming
with Haskell
Adriano Bonat
abonat@thoughtworks.com
@tanob

More Related Content

What's hot

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
John Cant
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional ruby
Functional rubyFunctional ruby
Functional ruby
Kerry Buckley
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Lec4
Lec4Lec4
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
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
Seminar fp
Seminar fpSeminar fp
Maps&hash tables
Maps&hash tablesMaps&hash tables
Maps&hash tables
Priyanka Rana
 
Data structures
Data structuresData structures
Data structures
Sneha Chopra
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
Joyjit Choudhury
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Lec5
Lec5Lec5
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
Madina Kamzina
 
Algorithms: I
Algorithms: IAlgorithms: I
Algorithms: I
Joyjit Choudhury
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
Shweta Bhatia
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
Knoldus Inc.
 

What's hot (20)

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional ruby
Functional rubyFunctional ruby
Functional ruby
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Lec4
Lec4Lec4
Lec4
 
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...
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Seminar fp
Seminar fpSeminar fp
Seminar fp
 
Maps&hash tables
Maps&hash tablesMaps&hash tables
Maps&hash tables
 
Data structures
Data structuresData structures
Data structures
 
Priority Queue
Priority QueuePriority Queue
Priority Queue
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Lec5
Lec5Lec5
Lec5
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8
 
Algorithms: I
Algorithms: IAlgorithms: I
Algorithms: I
 
Arrays.pptx
Arrays.pptxArrays.pptx
Arrays.pptx
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 

Similar to Functional Programming and Haskell - TWBR Away Day 2011

Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
IndicThreads
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
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
Michel Rijnders
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
Adriano Bonat
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
Nilt1234
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||
Ashwin Rao
 
L4 functions
L4 functionsL4 functions
L4 functions
mondalakash2012
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
Sergio Gil
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Munihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMunihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template Haskell
Matthew Pickering
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
Sebastian Rettig
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
Vincent Pradeilles
 
Functional Scala
Functional ScalaFunctional Scala
Functional Scala
Stan Lea
 
Python Basics
Python BasicsPython Basics
Python Basics
tusharpanda88
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
Naveenkumar Muguda
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
Taisuke Oe
 
Distributed Computing with Apache Hadoop. Introduction to MapReduce.
Distributed Computing with Apache Hadoop. Introduction to MapReduce.Distributed Computing with Apache Hadoop. Introduction to MapReduce.
Distributed Computing with Apache Hadoop. Introduction to MapReduce.
Konstantin V. Shvachko
 

Similar to Functional Programming and Haskell - TWBR Away Day 2011 (20)

Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
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
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||
 
L4 functions
L4 functionsL4 functions
L4 functions
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Munihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMunihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template Haskell
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Functional Scala
Functional ScalaFunctional Scala
Functional Scala
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 
Distributed Computing with Apache Hadoop. Introduction to MapReduce.
Distributed Computing with Apache Hadoop. Introduction to MapReduce.Distributed Computing with Apache Hadoop. Introduction to MapReduce.
Distributed Computing with Apache Hadoop. Introduction to MapReduce.
 

Recently uploaded

20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
Claudio Di Ciccio
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 

Recently uploaded (20)

20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
CAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on BlockchainCAKE: Sharing Slices of Confidential Data on Blockchain
CAKE: Sharing Slices of Confidential Data on Blockchain
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 

Functional Programming and Haskell - TWBR Away Day 2011

  • 2. Why FP? • Source of new ideas • Expressiveness • Multi-core CPUs • Different paradigm New ideas: Garbage collection (LISP) Type inference (simply typed lambda calculus) Generics Type classes Expressiveness: DSLs
  • 3. What is it? • Different programming paradigm • OO • Logic • Procedural • Functions are the main element in the language
  • 4. Function applications “Functional programming is so called because a program consists entirely of functions. [...] Typically the main function is defined in terms of other functions, which in turn are defined in terms of still more functions, until at the bottom level the functions are language primitives.” John Hughes, 1989 -Why functional programming matters
  • 5. Origin Alonzo Church developed Lambda Calculus as part of his investigations on Math foundations on 1936.
  • 6. Lambda Calculus • Variables • Expressions (e1 e2) • Lambda abstractions (λx. e)
  • 7. Lambda Calculus (I) • true = λxy. x • false = λxy. y • NOT a = (a)(false)(true) • a AND b = (a)(b)(false) • a OR b = (a)(true)(b) • a XOR b = (a)((b)(false)(true))(b)
  • 8. Haskell • Academic origin • Named in honor of Haskell Curry • Defined by a committee • First version released on 98 (Haskell 98)
  • 9. Features • Pureness • Type Inference • Algebraic datatypes (ADTs) • Pattern Matching • Lazyness • High Order Functions • Currification (aka Partial Application) • Type Classes • Monads
  • 10. Pureness • No side-effects • A function call can have no effect other than to compute its result • Expressions can be evaluated at any time • Programs are “referentially transparent” Good for: * reasoning * compiler optimization * concurrency
  • 11. Type Inference Let’s see the types for these declarations: four = 4 add x y = x + y emphasize x = x ++ “!”
  • 12. Algebraic datatypes Enumeration: data Season = Summer | Winter | Autumn | Spring Product: data Pair = Pair Int Int Sum: data Shape = Circle Float | Rect Float Float Polymorfic & Recursive: data Tree a = Leaf a | Node (Tree a) (Tree a)
  • 13. Algebraic datatypes (I) data Maybe a = Nothing | Just a data Either a b = Left a | Right b
  • 14. Pattern Matching Definition: sum [] = 0 sum (elem:rest) = elem + sum rest Application: sum [1,2,3,10]
  • 15. Pattern Matching (I) area (Circle rad) = pi * rad ^ 2 area (Rect width height) = width * height first (Pair value _) = value
  • 16. High Order Functions Functions which at least: • Receive functions as parameters • Return functions (aka curried functions)
  • 17. High Order Functions (I) map :: (a -> b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs
  • 18. Currification add :: Int -> Int -> Int add x y = x + y inc :: Int -> Int inc = add 1
  • 19. Lazyness • aka “call by need” • Expressions can be evaluated when necessary • Allows the use of infinite lists Being pure helps here
  • 20. Lazyness (I) Definition: even_numbers :: [Int] even_numbers = filter even [1..] Application: take 5 even_numbers
  • 21. Lazyness (II) fibs :: [Int] fibs = 0 : 1 : zipWith (+) fibs (tail fibs) From: http://en.wikipedia.org/wiki/Lazy_evaluation
  • 22. Type Classes • Created to solve the problem with numeric operator overload and equality testing • Some type classes defined by Haskell 98: • Eq • Read/Show
  • 23. Type Classes (I) class Eq a where (==), (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y) You can define what is called a “minimal implementation”.
  • 24. Type Classes (II) data User = User { name :: String } instance Eq User where user1 == user2 = name user1 == name user2 instance Show User where show user = name user
  • 25. Automatic Derivation data Season = Summer | Winter | Autumn | Spring deriving (Show, Eq) show Summer > “Summer” Summer /=Winter > True
  • 26. Monads • Adds to the type system a way to describe actions • The actions will happen in a certain order
  • 27. Monads • Common monads: • IO • State • Reader • Maybe
  • 28. Monads thing1 >>= x -> func1 x >>= y -> thing2 >>= _ -> func2 y >>= z -> return z do x <- thing1 y <- func1 x thing2 z <- func2 y return z sugar no-sugar
  • 29. Monads class Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b return :: a -> m a “return” is a bad name, it actually injects a value into the monadic type.
  • 30. Logger Monad type Log = [String] data Logger resultType = Logger (resultType, Log) deriving Show record x = Logger ((), [x]) instance Monad Logger where return value = Logger (value, []) prevLogger >>= nextAction = let Logger (prevResult, prevLog) = prevLogger Logger (newResult, newLog) = nextAction prevResult in Logger (newResult, prevLog ++ newLog)
  • 31. Testing? • Go read about QuickCheck!
  • 32. Want to learn more? Freely available online: http://book.realworldhaskell.org/
  • 33. Your Knowledge Portfolio "Learn at least one new language every year. [...] Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getting stuck in a rut." The Pragmatic Programmer