SlideShare a Scribd company logo
Functional Programming with Haskell
Ali Faradjpour
Agenda
● Functional Programming
● Haskell
● Haskell Types
● Haskell Functions
● Way to Monad
Imperative Vs. Declarative
int[] src = {1,2,3,4,5};
int result = 0;
for(int i = 0; i<src.length; i++){
int temp = src[i] * 2;
result += temp;
}
foldl (+) 0 . map (*2) $[1,2,3,4,5]
Vs.
Functional Programming
● central concept:
– result of a function is determined by its input, and
only by its input. There are no side-effects!
● This determinism removes a whole class of bugs found in
imperative programs:
– most bugs in large systems can be traced back to
side-effects - if not directly caused by them
Functional Programming
● Common pattern in functional programming:
– take a starting set of solutions and then you
apply transformations to those solutions and
filter them until you get the right ones.
● You need to think in terms of describing the overall
result that you want
● You do have to rethink your overall strategy for
solving the problem.
Haskell
● Haskell requires learning a new way to think,
not just new syntax for old concepts.
● This can be incredibly frustrating, as simple
tasks seem impossibly difficult.
Haskell
● Writing Haskell you want to learn to think in
terms of operations on aggregates:
– “do this to that collection.”
● Haskell doesn’t have any looping constructs
● Haskell data structures are immutable.
Haskell
● Pure Functional
● Lazy
● Strong typed
● Statically typed
● Immutable Data
● Higher-Order Functions
Strictness vs Non-Strictness
● A language is strict if it evaluates the arguments to a
function before it evaluates the function, A non-strict
language doesn’t.
Int taxTotal = getTotalTax();
Int baseFareTotal = getTotalBaseFare();
doSomeThing (taxTotal, baseFareTotal) ;
.
.
public void doSomeThing (….){
body Parameters' values
are available
Laziness vs Strictness
● evaluate as little as possible and delay evaluation as
long as possible
● Haskell is lazy, it is aggressively non-strict:
– it never evaluates anything before it absolutely
needs to.
● Lazy evaluation refers to implementation non-strictness
using thunks -- pointers to code which are replaced with a
value the first time they are executed.
lazyExmp param1 param2 = if someCondition then param1
else param2
lazyExmp func1 func2
Variables
● a variable is a name for some valid expression.
● given variable's value never varies during a
program's runtime
Haskell Variables
● A variable in Haskell is a name that is bound to
some value, rather than an abstraction of some
low-level concept of a memory cell.
Imperative Languages Haskell
a = 10 
.
.
a = 11 
Multiple declarations of ‘a’
Int height = 175;
Types
● Basic Types: Bool, Char, Int, Float, Integer,
String, Double
● type keyword: type synonyms
● :: shows type of expression
'a' :: Char
head :: [Int] -> Int
type Ratio = Double
type Point = (Int,Int)
Types
● Tuple is a sequence of values of different types
(False,True) :: (Bool,Bool)
(12,’a’,True) :: (Int,Char,Bool)
Types
● lists are a homogenous data structure
[1,2,3,4,5] “Haskell”
[(1,2),(3,4)] [[1,2],[5,6] ]
● Ranges [1..20] [2,4..20] [11,22..]
● list comprehension
[x*2 | x [1..10]] [2,4,6,8,10,12,14,16,18,20]
[x*2 | x [1..10], x*2 >= 12] [12,14,16,18,20]
[(x,y) | x [1..3], y [x..3]] 
Types
● Type Variables
func1 :: [Int] Int→
func2 :: [a] a (polymorphic function)→
Types
● Typeclass: a sort of interface that defines some
behavior.
● Eq, Ord, Show, Read, Enum, Bounded, Num,
Integral, Floating
func1 :: (Num a) => a → a → a
func1 x y = (x + y) / (x - y)
palindrome :: Eq a => [a] -> Bool
palindrome xs = reverse xs == xs
Types
● data keyword
data Answer = Yes | No | Unknown
data Shape = Circle Float Float Float
| Rectangle Float Float Float Float
Circle 10.0 20.0 5.0, Rectangle 10.0 20.0 10.0 20.0
data Point = Point Float Float deriving (Show)
Types
● data keyword
data Vector a = Vector a a a deriving (Show)
data Tree a = EmptyTree
| Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
exp: numsTree = Node 3 (Node 1 EmptyTree EmptyTree)
(Node 4 EmptyTree EmptyTree)
Types Cont.
● data keyword
data Maybe a = Just a | Nothing
data Either a b = Right a | Left b
Types Cont.
● class keyword
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x == y = not (x /= y)
x /= y = not (x == y)
Types Cont.
data TrafficLight = Red | Yellow | Green
instance Show TrafficLight where
show Red = "Red light"
show Yellow = "Yellow light"
show Green = "Green light"
data TrafficLight = Red | Yellow | Green
deriving (Show)
If & Case
if condition then expr1
Else expr2
if n ≥ 0 then n
else -n
case expression of pattern -> result
pattern -> result
pattern -> result
...
describeList xs = case xs of [] ->"empty."
[x] -> "a singleton list."
xs -> "a longer list."
Functions
● every expression and function must return
something
● Syntax: functions can't begin with uppercase
letters
functionName param1 ... paramN = expression
add :: a → a → a → a
add x y z = x + y + z
abs :: Int Int
abs n = if n 0 then n else -n≥
Functions Contd.
● Guards
abs n | n ≥ 0 = n
| otherwise = -n
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "THIN"
| weight / height ^ 2 <= 25.0 = "NORMAL"
| weight / height ^ 2 <= 30.0 = "FAT"
| otherwise = "You're a whale, congratulations!"
Functions Contd.
● Pattern Matching
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
Lambas
● Anonymous functions that are used because we
need some functions only once.
map (x -> x + 3) [1,6,3,2]
Curried functions
● Every function in Haskell officially only takes
one parameter, All the functions that accepted
several parameters have been curried functions.
multTwoWithNine = multThree 9
multTwoWithNine 2 3
> 54
multThree :: (Num a) => (a -> (a -> (a -> a)))
multThree x y z = x * y * z
Polymorphic Functions
●
A function is called polymorphic (“of many
forms”) if its type contains one or more type
variables
length :: [a]  Int
> length [False,True]
2
> length [1,2,3,4]
4
Higher order function
● Functions that can have functions as input or output
applyTwise:: (a → b) → a → b
applyTwise f x = f (f x)
(.) :: (b c) (a b) (a c)    
f . g = x f (g x)
● example: (.) returns the composition of two functions
as a single function
map (negate . sum . tail) [[1..5],[3..6],[1..7]]
Higher order function Cont.
● map
● filter
● foldl or foldr
map :: (a b) [a] [b]  
Map (+1) [1,3,5,7] [2,4,6,8]
filter :: (a Bool) [a] [a]  
filter even [1..10] [2,4,6,8,10]
fold :: (b -> a -> b) -> b -> a -> b
foldl (acc x -> acc + x) 0 [1,2,3] 6
Way to Monads
Real Values` Fancy Values
526
“This is a Window”
True
A
Just 5
Left “Error Msg”
IO String
Way to Monads
● Functor typeclass is basically for things that
can be mapped over.
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x leftsub rightsub) =
Node (f x) (fmap f leftsub) (fmap f rightsub)
Way to Monads
● Applicative
● we can't map a function that's inside a functor
over another functor with what fmap offers us
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
fmap :: (a -> b) -> f a -> f b
(<*>) :: f (a -> b) -> f a -> f b
[(+2),(*3)] <*> [5,7] [7,9,15,21]
Monad
●
have a value with a context, How to apply it to a
function that takes a normal a and returns a value
with a context?
fancyInput = Just 5
compFancyValue a = if a > 2 then Just (2 * a)
else Nothing
(apply) :: m a -> (a -> m b) -> m b
Monad
●
func1 :: Int → Maybe Int
func1 x = if x 'mod' 2 == 0 then Nothing else Just (2 * x)
●
func2 :: Int → Maybe Int
func2 x = if x 'mod' 3 == 0 then Nothing else Just (3 * x)
●
func3 :: Int → Maybe Int
func3 x = if x 'mod' 5 == 0 then Nothing else Just (5 * x)
● We'd like to compose them to get function:
funcComp :: Int → Maybe Int
● Multiplies input number by 30 unless is a multiple of 2,3,5
(in which case return Nothing)
Monad
● Defining k:
funcComp x = case func1 x of
Nothing → Nothing
Just y → case func2 y of
Nothing → Nothing
Just z → func3 z
Monad
apply :: Maybe a -> (a -> Maybe b) -> Maybe b
apply Nothing f = Nothing
apply (Just x) f = f x
funcComp x = func1 x `apply` func2 `apply` func3
Monad
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
x >> y = x >>= _ -> y
fail :: String -> m a
fail msg = error msg
instance Monad Maybe where
return x = Just x
Nothing >>= f = Nothing
Just x >>= f = f x
fail _ = Nothing
Monad
● Defining k without using monadic composition:
funcComp x = case func1 x of
Nothing → Nothing
Just y → case func2 y of
Nothing → Nothing
Just z → func3 z
● Defining k using Monadic composition:
funcComp x = func1 x >>= func2 >>= func3
Monad
● compose a bunch of monadic functions in the
Maybe monad easily.
● why the Maybe monad is important:
– it drastically cuts down on the boilerplate code
we have to write to chain Maybe-producing
functions together.
f7 x = f1 x >>= f2 >>= f3 >>= f4 >>= f5 >>= f6
Monad
func1 = Just 3>>= (x -> return (x+2))>>= (y -> return (y+3))
Just 5 Just 8
func1 = Just 3 >>= (x ->
return (x+2))>>= (y ->
return (y+3))
func1 = do
x <- Just 3
y <- return (x + 2)
return (y + 3)
Monad
● A Monad is a way to structure computations in
terms of values and sequences of computations
using those values.
● Sepration of composition and computation
Monad
● Why Do Monads Matter?
– Failure
– Dependence
– Uncertainty
– Destruction
Maybe a values represent computations that might have failed,
[a] values represent computations that have several results
(non-deterministic computations),
IO a values represent values that have side-effects
Haskell IDEs
● Leksah: It is written in Haskell, uses Gtk, and
runs on Linux, Windows and Mac OS X.
● EclipseFP: The Haskell plug-in for Eclipse
● Haskell-idea-plugin: IntelliJ IDEA plugin for
Haskell, based on idea.
● Integrate any favourite text editor (Vim, emacs,
Atom, …) with compiler and maker
Web Programming
● Web frameworks:
– Snap, Scotty, Sckop, Yesod, Happstack,
Mflow, …
● GUI:
– gtk2hs, hsqml, Threepenny-gui, …
● Database:
– HaskellDB, HSQL, HDBC
Performance
● Generally C has better performance
● Important functions could be written in C (using the excellent
foreign function interface in Haskell)
● C is often faster than Haskell. But in the real world
development times do matter, this isn't the case.
● Learn You a Haskell For Great Good
● Real World Haskell
● https://en.wikibooks.org/wiki/Haskell/
● wiki.haskell.org

More Related Content

What's hot

Polymorphism
PolymorphismPolymorphism
Polymorphism
Ahmed Za'anin
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
Ummar Hayat
 
LALR Parser Presentation ppt
LALR Parser Presentation pptLALR Parser Presentation ppt
LALR Parser Presentation ppt
WPVKP.COM
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
Dabbal Singh Mahara
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
sathish sak
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
AkhilaaReddy
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
Sheikh Monirul Hasan
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
talha ijaz
 
DSA (Data Structure and Algorithm) Questions
DSA (Data Structure and Algorithm) QuestionsDSA (Data Structure and Algorithm) Questions
DSA (Data Structure and Algorithm) Questions
RESHAN FARAZ
 
LR Parsing
LR ParsingLR Parsing
LR Parsing
Eelco Visser
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
VC Infotech
 
Hash tables and hash maps in python | Edureka
Hash tables and hash maps in python | EdurekaHash tables and hash maps in python | Edureka
Hash tables and hash maps in python | Edureka
Edureka!
 
C Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossainC Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossain
Sazzad Hossain, ITP, MBA, CSCA™
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
Wei-Ren Chen
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
eShikshak
 

What's hot (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Insertion sort bubble sort selection sort
Insertion sort bubble sort  selection sortInsertion sort bubble sort  selection sort
Insertion sort bubble sort selection sort
 
LALR Parser Presentation ppt
LALR Parser Presentation pptLALR Parser Presentation ppt
LALR Parser Presentation ppt
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Unit 3 stack
Unit   3 stackUnit   3 stack
Unit 3 stack
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
Stack of Data structure
Stack of Data structureStack of Data structure
Stack of Data structure
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
DSA (Data Structure and Algorithm) Questions
DSA (Data Structure and Algorithm) QuestionsDSA (Data Structure and Algorithm) Questions
DSA (Data Structure and Algorithm) Questions
 
Recurrences
RecurrencesRecurrences
Recurrences
 
LR Parsing
LR ParsingLR Parsing
LR Parsing
 
Function in c language(defination and declaration)
Function in c language(defination and declaration)Function in c language(defination and declaration)
Function in c language(defination and declaration)
 
Hash tables and hash maps in python | Edureka
Hash tables and hash maps in python | EdurekaHash tables and hash maps in python | Edureka
Hash tables and hash maps in python | Edureka
 
C Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossainC Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossain
 
Part II: LLVM Intermediate Representation
Part II: LLVM Intermediate RepresentationPart II: LLVM Intermediate Representation
Part II: LLVM Intermediate Representation
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
Functions in C
Functions in CFunctions in C
Functions in C
 

Viewers also liked

Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
John Cant
 
Agile Pratikler - Agile Turkey Sunumu
Agile Pratikler - Agile Turkey SunumuAgile Pratikler - Agile Turkey Sunumu
Agile Pratikler - Agile Turkey Sunumu
Murat Çabuk, MBA
 
Introduction to RESTful API Designs
Introduction to RESTful API DesignsIntroduction to RESTful API Designs
Introduction to RESTful API Designs
Roman Kuba
 
Beam me up, Scotty
Beam me up, ScottyBeam me up, Scotty
Beam me up, Scotty
Gianluca Padovani
 
You got ur Erlang in my Ruby
You got ur Erlang in my RubyYou got ur Erlang in my Ruby
You got ur Erlang in my Rubyelliando dias
 
Scotty Cameron
Scotty CameronScotty Cameron
Scotty Cameron
Birdsey
 
Scotty the Otter and his Adventure to You
Scotty the Otter and his Adventure to YouScotty the Otter and his Adventure to You
Scotty the Otter and his Adventure to You
ScottyOtty
 
Scotty, I need more speed - Koha tuning
Scotty, I need more speed - Koha tuningScotty, I need more speed - Koha tuning
Scotty, I need more speed - Koha tuning
Galen Charlton
 
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the BrandScotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
Scotty Morrison
 
El Protocolo de Kioto
El Protocolo de KiotoEl Protocolo de Kioto
El Protocolo de Kioto
IES Turina/Rodrigo/Itaca/Palomeras
 
Functional Programming and Haskell - TWBR Away Day 2011
Functional Programming and Haskell - TWBR Away Day 2011Functional Programming and Haskell - TWBR Away Day 2011
Functional Programming and Haskell - TWBR Away Day 2011
Adriano Bonat
 
Fotos graciosas 33657
Fotos graciosas 33657Fotos graciosas 33657
Fotos graciosas 33657serviojapon
 
Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy WayYC Ling
 
Introduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScriptIntroduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScript
Will Kurt
 
Neo4j
Neo4jNeo4j
Neo4j
Von Stark
 
Haskell study 8
Haskell study 8Haskell study 8
Haskell study 8
Nam Hyeonuk
 
Building a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.jsBuilding a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.js
Nicolas Hery
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
Bikram Thapa
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
osfameron
 
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
 

Viewers also liked (20)

Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Agile Pratikler - Agile Turkey Sunumu
Agile Pratikler - Agile Turkey SunumuAgile Pratikler - Agile Turkey Sunumu
Agile Pratikler - Agile Turkey Sunumu
 
Introduction to RESTful API Designs
Introduction to RESTful API DesignsIntroduction to RESTful API Designs
Introduction to RESTful API Designs
 
Beam me up, Scotty
Beam me up, ScottyBeam me up, Scotty
Beam me up, Scotty
 
You got ur Erlang in my Ruby
You got ur Erlang in my RubyYou got ur Erlang in my Ruby
You got ur Erlang in my Ruby
 
Scotty Cameron
Scotty CameronScotty Cameron
Scotty Cameron
 
Scotty the Otter and his Adventure to You
Scotty the Otter and his Adventure to YouScotty the Otter and his Adventure to You
Scotty the Otter and his Adventure to You
 
Scotty, I need more speed - Koha tuning
Scotty, I need more speed - Koha tuningScotty, I need more speed - Koha tuning
Scotty, I need more speed - Koha tuning
 
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the BrandScotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
Scotty Morrison Salesforce.com New HIre TED Talk: Behind the Brand
 
El Protocolo de Kioto
El Protocolo de KiotoEl Protocolo de Kioto
El Protocolo de Kioto
 
Functional Programming and Haskell - TWBR Away Day 2011
Functional Programming and Haskell - TWBR Away Day 2011Functional Programming and Haskell - TWBR Away Day 2011
Functional Programming and Haskell - TWBR Away Day 2011
 
Fotos graciosas 33657
Fotos graciosas 33657Fotos graciosas 33657
Fotos graciosas 33657
 
Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy Way
 
Introduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScriptIntroduction to Functional Programming with Haskell and JavaScript
Introduction to Functional Programming with Haskell and JavaScript
 
Neo4j
Neo4jNeo4j
Neo4j
 
Haskell study 8
Haskell study 8Haskell study 8
Haskell study 8
 
Building a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.jsBuilding a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.js
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
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!
 

Similar to Functional programming with haskell

A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
Jordan Open Source Association
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
rkaippully
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, ML
Simone Di Maulo
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
Mauro Palsgraaf
 
openMP loop parallelization
openMP loop parallelizationopenMP loop parallelization
openMP loop parallelization
Albert DeFusco
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
Maneesh Chaturvedi
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
AnishaJ7
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
Sheik Uduman Ali
 

Similar to Functional programming with haskell (20)

A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
09. haskell Context
09. haskell Context09. haskell Context
09. haskell Context
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, ML
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
 
openMP loop parallelization
openMP loop parallelizationopenMP loop parallelization
openMP loop parallelization
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 

Recently uploaded

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
QuickwayInfoSystems3
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
abdulrafaychaudhry
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 

Recently uploaded (20)

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Enterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptxEnterprise Software Development with No Code Solutions.pptx
Enterprise Software Development with No Code Solutions.pptx
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)Introduction to Pygame (Lecture 7 Python Game Development)
Introduction to Pygame (Lecture 7 Python Game Development)
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 

Functional programming with haskell

  • 1. Functional Programming with Haskell Ali Faradjpour
  • 2. Agenda ● Functional Programming ● Haskell ● Haskell Types ● Haskell Functions ● Way to Monad
  • 3. Imperative Vs. Declarative int[] src = {1,2,3,4,5}; int result = 0; for(int i = 0; i<src.length; i++){ int temp = src[i] * 2; result += temp; } foldl (+) 0 . map (*2) $[1,2,3,4,5] Vs.
  • 4. Functional Programming ● central concept: – result of a function is determined by its input, and only by its input. There are no side-effects! ● This determinism removes a whole class of bugs found in imperative programs: – most bugs in large systems can be traced back to side-effects - if not directly caused by them
  • 5. Functional Programming ● Common pattern in functional programming: – take a starting set of solutions and then you apply transformations to those solutions and filter them until you get the right ones. ● You need to think in terms of describing the overall result that you want ● You do have to rethink your overall strategy for solving the problem.
  • 6. Haskell ● Haskell requires learning a new way to think, not just new syntax for old concepts. ● This can be incredibly frustrating, as simple tasks seem impossibly difficult.
  • 7. Haskell ● Writing Haskell you want to learn to think in terms of operations on aggregates: – “do this to that collection.” ● Haskell doesn’t have any looping constructs ● Haskell data structures are immutable.
  • 8. Haskell ● Pure Functional ● Lazy ● Strong typed ● Statically typed ● Immutable Data ● Higher-Order Functions
  • 9. Strictness vs Non-Strictness ● A language is strict if it evaluates the arguments to a function before it evaluates the function, A non-strict language doesn’t. Int taxTotal = getTotalTax(); Int baseFareTotal = getTotalBaseFare(); doSomeThing (taxTotal, baseFareTotal) ; . . public void doSomeThing (….){ body Parameters' values are available
  • 10. Laziness vs Strictness ● evaluate as little as possible and delay evaluation as long as possible ● Haskell is lazy, it is aggressively non-strict: – it never evaluates anything before it absolutely needs to. ● Lazy evaluation refers to implementation non-strictness using thunks -- pointers to code which are replaced with a value the first time they are executed. lazyExmp param1 param2 = if someCondition then param1 else param2 lazyExmp func1 func2
  • 11. Variables ● a variable is a name for some valid expression. ● given variable's value never varies during a program's runtime
  • 12. Haskell Variables ● A variable in Haskell is a name that is bound to some value, rather than an abstraction of some low-level concept of a memory cell. Imperative Languages Haskell a = 10  . . a = 11  Multiple declarations of ‘a’ Int height = 175;
  • 13. Types ● Basic Types: Bool, Char, Int, Float, Integer, String, Double ● type keyword: type synonyms ● :: shows type of expression 'a' :: Char head :: [Int] -> Int type Ratio = Double type Point = (Int,Int)
  • 14. Types ● Tuple is a sequence of values of different types (False,True) :: (Bool,Bool) (12,’a’,True) :: (Int,Char,Bool)
  • 15. Types ● lists are a homogenous data structure [1,2,3,4,5] “Haskell” [(1,2),(3,4)] [[1,2],[5,6] ] ● Ranges [1..20] [2,4..20] [11,22..] ● list comprehension [x*2 | x [1..10]] [2,4,6,8,10,12,14,16,18,20] [x*2 | x [1..10], x*2 >= 12] [12,14,16,18,20] [(x,y) | x [1..3], y [x..3]] 
  • 16. Types ● Type Variables func1 :: [Int] Int→ func2 :: [a] a (polymorphic function)→
  • 17. Types ● Typeclass: a sort of interface that defines some behavior. ● Eq, Ord, Show, Read, Enum, Bounded, Num, Integral, Floating func1 :: (Num a) => a → a → a func1 x y = (x + y) / (x - y) palindrome :: Eq a => [a] -> Bool palindrome xs = reverse xs == xs
  • 18. Types ● data keyword data Answer = Yes | No | Unknown data Shape = Circle Float Float Float | Rectangle Float Float Float Float Circle 10.0 20.0 5.0, Rectangle 10.0 20.0 10.0 20.0 data Point = Point Float Float deriving (Show)
  • 19. Types ● data keyword data Vector a = Vector a a a deriving (Show) data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) exp: numsTree = Node 3 (Node 1 EmptyTree EmptyTree) (Node 4 EmptyTree EmptyTree)
  • 20. Types Cont. ● data keyword data Maybe a = Just a | Nothing data Either a b = Right a | Left b
  • 21. Types Cont. ● class keyword class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool x == y = not (x /= y) x /= y = not (x == y)
  • 22. Types Cont. data TrafficLight = Red | Yellow | Green instance Show TrafficLight where show Red = "Red light" show Yellow = "Yellow light" show Green = "Green light" data TrafficLight = Red | Yellow | Green deriving (Show)
  • 23. If & Case if condition then expr1 Else expr2 if n ≥ 0 then n else -n case expression of pattern -> result pattern -> result pattern -> result ... describeList xs = case xs of [] ->"empty." [x] -> "a singleton list." xs -> "a longer list."
  • 24. Functions ● every expression and function must return something ● Syntax: functions can't begin with uppercase letters functionName param1 ... paramN = expression add :: a → a → a → a add x y z = x + y + z abs :: Int Int abs n = if n 0 then n else -n≥
  • 25. Functions Contd. ● Guards abs n | n ≥ 0 = n | otherwise = -n bmiTell :: (RealFloat a) => a -> a -> String bmiTell weight height | weight / height ^ 2 <= 18.5 = "THIN" | weight / height ^ 2 <= 25.0 = "NORMAL" | weight / height ^ 2 <= 30.0 = "FAT" | otherwise = "You're a whale, congratulations!"
  • 26. Functions Contd. ● Pattern Matching factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1) sum' :: (Num a) => [a] -> a sum' [] = 0 sum' (x:xs) = x + sum' xs
  • 27. Lambas ● Anonymous functions that are used because we need some functions only once. map (x -> x + 3) [1,6,3,2]
  • 28. Curried functions ● Every function in Haskell officially only takes one parameter, All the functions that accepted several parameters have been curried functions. multTwoWithNine = multThree 9 multTwoWithNine 2 3 > 54 multThree :: (Num a) => (a -> (a -> (a -> a))) multThree x y z = x * y * z
  • 29. Polymorphic Functions ● A function is called polymorphic (“of many forms”) if its type contains one or more type variables length :: [a]  Int > length [False,True] 2 > length [1,2,3,4] 4
  • 30. Higher order function ● Functions that can have functions as input or output applyTwise:: (a → b) → a → b applyTwise f x = f (f x) (.) :: (b c) (a b) (a c)     f . g = x f (g x) ● example: (.) returns the composition of two functions as a single function map (negate . sum . tail) [[1..5],[3..6],[1..7]]
  • 31. Higher order function Cont. ● map ● filter ● foldl or foldr map :: (a b) [a] [b]   Map (+1) [1,3,5,7] [2,4,6,8] filter :: (a Bool) [a] [a]   filter even [1..10] [2,4,6,8,10] fold :: (b -> a -> b) -> b -> a -> b foldl (acc x -> acc + x) 0 [1,2,3] 6
  • 32. Way to Monads Real Values` Fancy Values 526 “This is a Window” True A Just 5 Left “Error Msg” IO String
  • 33. Way to Monads ● Functor typeclass is basically for things that can be mapped over. class Functor f where fmap :: (a -> b) -> f a -> f b instance Functor [] where fmap = map instance Functor Tree where fmap f EmptyTree = EmptyTree fmap f (Node x leftsub rightsub) = Node (f x) (fmap f leftsub) (fmap f rightsub)
  • 34. Way to Monads ● Applicative ● we can't map a function that's inside a functor over another functor with what fmap offers us class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b fmap :: (a -> b) -> f a -> f b (<*>) :: f (a -> b) -> f a -> f b [(+2),(*3)] <*> [5,7] [7,9,15,21]
  • 35. Monad ● have a value with a context, How to apply it to a function that takes a normal a and returns a value with a context? fancyInput = Just 5 compFancyValue a = if a > 2 then Just (2 * a) else Nothing (apply) :: m a -> (a -> m b) -> m b
  • 36. Monad ● func1 :: Int → Maybe Int func1 x = if x 'mod' 2 == 0 then Nothing else Just (2 * x) ● func2 :: Int → Maybe Int func2 x = if x 'mod' 3 == 0 then Nothing else Just (3 * x) ● func3 :: Int → Maybe Int func3 x = if x 'mod' 5 == 0 then Nothing else Just (5 * x) ● We'd like to compose them to get function: funcComp :: Int → Maybe Int ● Multiplies input number by 30 unless is a multiple of 2,3,5 (in which case return Nothing)
  • 37. Monad ● Defining k: funcComp x = case func1 x of Nothing → Nothing Just y → case func2 y of Nothing → Nothing Just z → func3 z
  • 38. Monad apply :: Maybe a -> (a -> Maybe b) -> Maybe b apply Nothing f = Nothing apply (Just x) f = f x funcComp x = func1 x `apply` func2 `apply` func3
  • 39. Monad class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b x >> y = x >>= _ -> y fail :: String -> m a fail msg = error msg instance Monad Maybe where return x = Just x Nothing >>= f = Nothing Just x >>= f = f x fail _ = Nothing
  • 40. Monad ● Defining k without using monadic composition: funcComp x = case func1 x of Nothing → Nothing Just y → case func2 y of Nothing → Nothing Just z → func3 z ● Defining k using Monadic composition: funcComp x = func1 x >>= func2 >>= func3
  • 41. Monad ● compose a bunch of monadic functions in the Maybe monad easily. ● why the Maybe monad is important: – it drastically cuts down on the boilerplate code we have to write to chain Maybe-producing functions together. f7 x = f1 x >>= f2 >>= f3 >>= f4 >>= f5 >>= f6
  • 42. Monad func1 = Just 3>>= (x -> return (x+2))>>= (y -> return (y+3)) Just 5 Just 8 func1 = Just 3 >>= (x -> return (x+2))>>= (y -> return (y+3)) func1 = do x <- Just 3 y <- return (x + 2) return (y + 3)
  • 43. Monad ● A Monad is a way to structure computations in terms of values and sequences of computations using those values. ● Sepration of composition and computation
  • 44. Monad ● Why Do Monads Matter? – Failure – Dependence – Uncertainty – Destruction Maybe a values represent computations that might have failed, [a] values represent computations that have several results (non-deterministic computations), IO a values represent values that have side-effects
  • 45.
  • 46. Haskell IDEs ● Leksah: It is written in Haskell, uses Gtk, and runs on Linux, Windows and Mac OS X. ● EclipseFP: The Haskell plug-in for Eclipse ● Haskell-idea-plugin: IntelliJ IDEA plugin for Haskell, based on idea. ● Integrate any favourite text editor (Vim, emacs, Atom, …) with compiler and maker
  • 47. Web Programming ● Web frameworks: – Snap, Scotty, Sckop, Yesod, Happstack, Mflow, … ● GUI: – gtk2hs, hsqml, Threepenny-gui, … ● Database: – HaskellDB, HSQL, HDBC
  • 48. Performance ● Generally C has better performance ● Important functions could be written in C (using the excellent foreign function interface in Haskell) ● C is often faster than Haskell. But in the real world development times do matter, this isn't the case.
  • 49. ● Learn You a Haskell For Great Good ● Real World Haskell ● https://en.wikibooks.org/wiki/Haskell/ ● wiki.haskell.org