SlideShare a Scribd company logo
1 of 34
Download to read offline
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 lazinessJohan Tibell
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn 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 HaskellJohan Tibell
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
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 programmingVisnuDharsini
 
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 | EdurekaEdureka!
 
Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Gdg almaty. Функциональное программирование в Java 8
Gdg almaty. Функциональное программирование в Java 8Madina Kamzina
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In ScalaKnoldus 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 FutureIndicThreads
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco 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 HaskellMichel Rijnders
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTWAdriano 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 LISPNilt1234
 
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
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevJavaDayUA
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Munihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMunihac 2018 - Beautiful Template Haskell
Munihac 2018 - Beautiful Template HaskellMatthew Pickering
 
Functional Scala
Functional ScalaFunctional Scala
Functional ScalaStan Lea
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software DevelopmentNaveenkumar 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): Day1Taisuke 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

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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
 
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
 
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
 
[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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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
 
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
 
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
 
[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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 

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