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 (20)

PDF
Reasoning about laziness
Johan Tibell
 
PDF
Haskell for data science
John Cant
 
PDF
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
PDF
High-Performance Haskell
Johan Tibell
 
PPT
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
KEY
Functional ruby
Kerry Buckley
 
PPT
Rewriting Java In Scala
Skills Matter
 
PDF
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
PPTX
Functions in advanced programming
VisnuDharsini
 
PPTX
Seminar fp
VeerapatBoonvanich1
 
PPT
Maps&hash tables
Priyanka Rana
 
PPTX
Data structures
Sneha Chopra
 
PDF
Priority Queue
Joyjit Choudhury
 
PDF
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
PDF
Gdg almaty. Функциональное программирование в Java 8
Madina Kamzina
 
PDF
Algorithms: I
Joyjit Choudhury
 
PPTX
Arrays.pptx
Shweta Bhatia
 
ODP
Collections In Scala
Knoldus Inc.
 
Reasoning about laziness
Johan Tibell
 
Haskell for data science
John Cant
 
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
High-Performance Haskell
Johan Tibell
 
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional ruby
Kerry Buckley
 
Rewriting Java In Scala
Skills Matter
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
Functions in advanced programming
VisnuDharsini
 
Maps&hash tables
Priyanka Rana
 
Data structures
Sneha Chopra
 
Priority Queue
Joyjit Choudhury
 
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Gdg almaty. Функциональное программирование в Java 8
Madina Kamzina
 
Algorithms: I
Joyjit Choudhury
 
Arrays.pptx
Shweta Bhatia
 
Collections In Scala
Knoldus Inc.
 

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

PDF
The Next Great Functional Programming Language
John De Goes
 
PDF
Introduction to Functional Languages
suthi
 
PDF
[FLOLAC'14][scm] Functional Programming Using Haskell
Functional Thursday
 
PPTX
Functional programming seminar (haskell)
Bikram Thapa
 
KEY
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
PDF
Functional Programming #FTW
Adriano Bonat
 
PDF
Why is Haskell so hard! (And how to deal with it?)
Saurabh Nanda
 
PDF
Humble introduction to category theory in haskell
Jongsoo Lee
 
PPT
Functional Programming Past Present Future
IndicThreads
 
PPS
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
PDF
Functional programming using haskell notes iitk
benevolent001
 
PPTX
Functional programming
Heman Gandhi
 
PDF
10. haskell Modules
Sebastian Rettig
 
PDF
Functional programming
ijcd
 
PDF
OOP and FP
Mario Fusco
 
PDF
Real World Haskell: Lecture 3
Bryan O'Sullivan
 
PDF
Making the most of lambdas
Robert Zych
 
PPTX
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
PPTX
Good functional programming is good programming
kenbot
 
PPTX
The joy of functional programming
Steve Zhang
 
The Next Great Functional Programming Language
John De Goes
 
Introduction to Functional Languages
suthi
 
[FLOLAC'14][scm] Functional Programming Using Haskell
Functional Thursday
 
Functional programming seminar (haskell)
Bikram Thapa
 
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
Functional Programming #FTW
Adriano Bonat
 
Why is Haskell so hard! (And how to deal with it?)
Saurabh Nanda
 
Humble introduction to category theory in haskell
Jongsoo Lee
 
Functional Programming Past Present Future
IndicThreads
 
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
Functional programming using haskell notes iitk
benevolent001
 
Functional programming
Heman Gandhi
 
10. haskell Modules
Sebastian Rettig
 
Functional programming
ijcd
 
OOP and FP
Mario Fusco
 
Real World Haskell: Lecture 3
Bryan O'Sullivan
 
Making the most of lambdas
Robert Zych
 
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
Good functional programming is good programming
kenbot
 
The joy of functional programming
Steve Zhang
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Ad

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