SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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.
 

La actualidad más candente (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 a 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 a 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.
 

Último

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Último (20)

Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

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