SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
Beginning Haskell
Tom Prior
@priortd
www.prigrammer.com
Newsweaver
Quick Search on Quora
Explanation?
• I can’t just print hello world!

• Its purity means things can often be explained in relation to
maths

• Use of whitespace and annoying compilation errors from it

• Strict type system and purity means that programmers forced
to stick to a purely functional style
Sounds a bit complicated !
MATHS
MONADS
FUNCTORS
APPLICATIVES
I just want to print Hello World !
public class HelloWorld {



public static void main (String [] args) {


System.out.println("Hello World");

}


}


module HelloWorld where



main :: IO()

main = putStrLn("Hello World")
REPL Playground!
➜ ~ ghci
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /Users/tom/.ghci
ghci> print "Hello World"
"Hello World"
ghci> 1 + 1
2
ghci> "Haskell " ++ "is cool"
"Haskell is cool"
ghci> sum [1, 2, 3]
6
ghci> :l HelloWorld.hs
[1 of 1] Compiling HelloWorld ( Helloworld.hs, interpreted )
Ok, modules loaded: HelloWorld.
ghci> main
Hello World
ghci>
Katas Up and Running in
No Time
With basic loops and logic
The Infamous Palindrome
h u z z a h
u z z a
h u z z u h
u z z u
z z
Imperative Java Solution
public static boolean isPalindrome(String str) {



int strEndIndex = str.length() - 1;



for(int i = strEndIndex; i > (strEndIndex/2); i--)

if(str.charAt(i) != str.charAt(strEndIndex - i))

return false;



return true;

}
Haskell Palindrome
Logic and Recursion
isPalindrome :: String -> Bool

isPalindrome str =

loop strEndIndex where



strEndIndex = length str - 1

loop i =

if i <= (div strEndIndex 2) then True

else if (str !! i) /= str !! (strEndIndex - i) then False

else loop (i - 1)
DISCLAIMER: Not the Nicest Haskell Code, but gets us started !
Guards
isPalindrome :: String -> Bool

isPalindrome str =

loop strEndIndex where



strEndIndex = length str - 1

loop i

| i <= (div strEndIndex 2) = True

| (str !! i) /= str !! (strEndIndex - i) = False

| otherwise = loop (i - 1)
Refining the Palindrome
Pattern Matching and Recursion
isPalindrome :: String -> Bool

isPalindrome str =

case str of

[] -> True

x : [] -> True

x1 : x2 : [] -> x1 == x2

x1 : xs -> x1 == last xs && isPalindrome (init xs)
Refining the Palindrome
Pattern matching without case
isPalindrome :: String -> Bool

isPalindrome [] = True

isPalindrome (x : []) = True

isPalindrome (x1 : x2 : []) = x1 == x2

isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
List Type and Pattern Match
ghci> :info []
data [] a = [] | a : [a] -- Defined in ‘GHC.Types’
ghci> 1 : 2 : 3 : []
[1,2,3]
ghci> [1,2,3]
[1,2,3]
1
2
3
[]
Refining the Palindrome
Is whatever a palindrome?
isPalindrome :: (Eq a) => [a] -> Bool

isPalindrome [] = True

isPalindrome (x : []) = True

isPalindrome (x1 : x2 : []) = x1 == x2

isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
ghci> isPalindrome [1,2,3]
False
ghci> isPalindrome [1,2,1]
True
Why the (Eq a) => ?
Type Classes
ghci> :info Eq
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
ghci> :l HaskellPlayground.hs
[1 of 1] Compiling HaskellPlayground
( HaskellPlayground.hs, interpreted )
HaskellPlayground.hs:35:31: error:
• No instance for (Eq a) arising from a use of ‘==’
Possible fix:
add (Eq a) to the context of
the type signature for:
isPalindrome :: [a] -> Bool
isPalindrome :: [a] -> Bool
isPalindrome :: (Eq a) => [a] -> Bool

isPalindrome [] = True

isPalindrome (x : []) = True

isPalindrome (x1 : x2 : []) = x1 == x2

isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
I want to call isPalindrome
on my own Type
data Book =

Single String

| Trilogy String

| Series String

deriving (Show)
data Book =

Single { title :: String }

| Trilogy { title :: String }

| Series { title :: String }

deriving (Show)
ghci> let b = Trilogy {title = "Lord of the Rings"}
ghci> b
Trilogy {title = "Lord of the Rings”}
ghci> title b
"Lord of the Rings"
ghci> let b2 = b {title = "Lord of the Rings Version 2"}
ghci> b2
Trilogy {title = "Lord of the Rings Version 2"}
ghci> b
Trilogy {title = "Lord of the Rings"}
Is my book list a
palindrome?
ghci> isPalindrome [(Single "The Hobbit"), (Trilogy
"Lord of the Rings"), (Single "The Hobbit")]
<interactive>:22:1: error:
• No instance for (Eq Book) arising from a use
of ‘isPalindrome’
Comparing my books
instance Eq Book where

(==) (Single t1) (Single t2) = t1 == t2

(==) (Trilogy t1) (Trilogy t2) = t1 == t2

(==) (Series t1) (Series t2) = t1 == t2

(==) _ _ = False
ghci> :info Eq
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
ghci> isPalindrome [(Single "The Hobbit"), (Trilogy "Lord of the Rings"),
(Single "The Hobbit")]
True
ghci> isPalindrome [(Single "The Hobbit"), (Trilogy "Lord of the Rings"),
(Series "The Hobbit")]
False
Now are my books a
palindrome?
Derving Type Classes
data Book =

Single String

| Trilogy String

| Series String

deriving (Show, Eq)
ghci> :info Show
class Show a where
….
show :: a -> String
….
Are they all palindromes?
["racecar","wow","huzzah"]
allPalindromes = areAllPalindromes [

[(Single "S"), (Trilogy "T"), (Single "S")],

[(Series "S"), (Trilogy "T"), (Series "S")]

]
allPalindromes = areAllPalindromes [

[(Single "S"), (Trilogy "T"), (Single "S")],

[(Series "S"), (Trilogy "T"), (Series "S2")]

]
Are they all palindromes?
Almost imperative style loop
areAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes listOfLists =

loop listOfLists where

loop lOfl =

case lOfl of

[] -> True

(x : xs) -> isPalindrome x && loop xs
ghci> areAllPalindromes ["racecar", "wow", "huzzuh"]
True
ghci> areAllPalindromes ["racecar", "wow", "huzzah"]
False
Are they all palindromes?
Refining the recursion
areAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes [] = True

areAllPalindromes (x : xs) = isPalindrome x && areAllPalindromes xs
Are they all palindromes?
FoldareAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes lOfLs =

foldr (x result -> isPalindrome x && result) True lOfLs
["racecar", "wow", "huzzah"]
reduces as follows:
(isPalindrome "racecar") True
&&
((isPalindrome "wow") True
&&
((isPalindrome “huzzah") False
&& True)))
Point Free Niceness !
palindromeWithAnding :: (Eq a) => [a] -> Bool -> Bool

palindromeWithAnding x b = (&&) (isPalindrome x) b
ghci> palindromeWithAnding "huzzuh" False
False
ghci> palindromeWithAnding "huzzuh" True
True
Function by Name Binding..
areAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes lOfLs = foldr palindromeWithAnding True
lOfLs
Map and then Fold
ghci> map isPalindrome ["racecar", "wow", “huzzah"]
[True,True,False]
areAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes lOfLs =
foldr (x result -> x && result) True (map isPalindrome lOfLs)
WITH POINT FREE &&
areAllPalindromes :: (Eq a) => [[a]] -> Bool

areAllPalindromes lOfLs =
foldr (&&) True (map isPalindrome lOfLs)
Automatic Currying
Niceness !map isPalindrome lOfLs
ghci> :t map
map :: (a -> b) -> [a] -> [b]
So..
map func list
pseudocode
map = func -> list -> ‘map this list with func function’
map isPalindrome
list -> ‘map this list with isPalindrome function’
areAllPalindromes lOfLs = (foldr (&&) True) (map isPalindrome lOfLs)
map and then fold
fold . map
areAllPalindromes lOfLs = (foldr (&&) True) . (map isPalindrome) $ lOfLs
areAllPalindromes = (foldr (&&) True) . (map isPalindrome)
areAllPalindromes = foldr (&&) True . map isPalindrome
Function Composition
Niceness !
Composition and Point Free
Pipeline Declaration
Focusing on Transformations
Map with isPalindrome
Fold with &&
["racecar", "wow", "huzzuh"]
[True, True, True]
True
onlyPalindromes :: (Eq a) => [[a]] -> [[a]]

onlyPalindromes xs = filter isPalindrome xs
ghci> onlyPalindromes ["racecar", "huzzah", "wow"]
[“racecar","wow"]
USING AUTOMATIC CURRYING
onlyPalindromes :: (Eq a) => [[a]] -> [[a]]

onlyPalindromes = filter isPalindrome
Filter Palindromes
Haskell Laziness
ghci> length ["racecar", "huzzah", undefined]
3
ghci> length (map head ["racecar", "huzzah", undefined])
3
ghci> take 2 (map head ["racecar", "huzzah", undefined])
“rh"
ghci> take 3 (map head ["racecar", "huzzah", undefined])
"rh*** Exception: Prelude.undefined
ghci> take 1 (filter isPalindrome ["racecar", "huzzah", undefined])
[“racecar"]
ghci> take 2 (filter isPalindrome ["racecar", "huzzah", undefined])
["racecar"*** Exception: Prelude.undefined
How do I get started
https://www.haskell.org/platform/
Start a REPL with
➜ ~ ghci
GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /Users/tom/.ghci
ghci>
Play with the examples from this talk
GitHub priort
Books
haskellbook.com

Más contenido relacionado

La actualidad más candente

Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
 

La actualidad más candente (13)

Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real World
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 

Destacado

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 
Effective akka scalaio
Effective akka scalaioEffective akka scalaio
Effective akka scalaio
shinolajla
 
C*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with CassandraC*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with Cassandra
DataStax
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloud
Idan Fridman
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
mircodotta
 

Destacado (20)

Haskell for the Real World
Haskell for the Real WorldHaskell for the Real World
Haskell for the Real World
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structures
 
Spring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4DevelopersSpring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4Developers
 
Chicago Hadoop Users Group: Enterprise Data Workflows
Chicago Hadoop Users Group: Enterprise Data WorkflowsChicago Hadoop Users Group: Enterprise Data Workflows
Chicago Hadoop Users Group: Enterprise Data Workflows
 
Reactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons LearnedReactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons Learned
 
The no-framework Scala Dependency Injection Framework
The no-framework Scala Dependency Injection FrameworkThe no-framework Scala Dependency Injection Framework
The no-framework Scala Dependency Injection Framework
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Effective akka scalaio
Effective akka scalaioEffective akka scalaio
Effective akka scalaio
 
Actor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in AkkaActor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in Akka
 
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
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
 
Haskell
HaskellHaskell
Haskell
 
C*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with CassandraC*ollege Credit: Creating Your First App in Java with Cassandra
C*ollege Credit: Creating Your First App in Java with Cassandra
 
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
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloud
 
Effective Actors
Effective ActorsEffective Actors
Effective Actors
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
 
Curator intro
Curator introCurator intro
Curator intro
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)
 

Similar a Beginning Haskell, Dive In, Its Not That Scary!

Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
aztack
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
Ian Bishop
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
Mike Fogus
 

Similar a Beginning Haskell, Dive In, Its Not That Scary! (20)

Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212
 
XKE Typeclass
XKE TypeclassXKE Typeclass
XKE Typeclass
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Music as data
Music as dataMusic as data
Music as data
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202
 
Python
PythonPython
Python
 
The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210The Ring programming language version 1.9 book - Part 31 of 210
The Ring programming language version 1.9 book - Part 31 of 210
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Último (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 

Beginning Haskell, Dive In, Its Not That Scary!

  • 3. Explanation? • I can’t just print hello world! • Its purity means things can often be explained in relation to maths • Use of whitespace and annoying compilation errors from it • Strict type system and purity means that programmers forced to stick to a purely functional style
  • 4. Sounds a bit complicated ! MATHS MONADS FUNCTORS APPLICATIVES
  • 5. I just want to print Hello World ! public class HelloWorld {
 
 public static void main (String [] args) { 
 System.out.println("Hello World");
 } 
 } 
 module HelloWorld where
 
 main :: IO()
 main = putStrLn("Hello World")
  • 6. REPL Playground! ➜ ~ ghci GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /Users/tom/.ghci ghci> print "Hello World" "Hello World" ghci> 1 + 1 2 ghci> "Haskell " ++ "is cool" "Haskell is cool" ghci> sum [1, 2, 3] 6 ghci> :l HelloWorld.hs [1 of 1] Compiling HelloWorld ( Helloworld.hs, interpreted ) Ok, modules loaded: HelloWorld. ghci> main Hello World ghci>
  • 7. Katas Up and Running in No Time With basic loops and logic
  • 8. The Infamous Palindrome h u z z a h u z z a
  • 9. h u z z u h u z z u z z
  • 10. Imperative Java Solution public static boolean isPalindrome(String str) {
 
 int strEndIndex = str.length() - 1;
 
 for(int i = strEndIndex; i > (strEndIndex/2); i--)
 if(str.charAt(i) != str.charAt(strEndIndex - i))
 return false;
 
 return true;
 }
  • 11. Haskell Palindrome Logic and Recursion isPalindrome :: String -> Bool
 isPalindrome str =
 loop strEndIndex where
 
 strEndIndex = length str - 1
 loop i =
 if i <= (div strEndIndex 2) then True
 else if (str !! i) /= str !! (strEndIndex - i) then False
 else loop (i - 1) DISCLAIMER: Not the Nicest Haskell Code, but gets us started !
  • 12. Guards isPalindrome :: String -> Bool
 isPalindrome str =
 loop strEndIndex where
 
 strEndIndex = length str - 1
 loop i
 | i <= (div strEndIndex 2) = True
 | (str !! i) /= str !! (strEndIndex - i) = False
 | otherwise = loop (i - 1)
  • 13. Refining the Palindrome Pattern Matching and Recursion isPalindrome :: String -> Bool
 isPalindrome str =
 case str of
 [] -> True
 x : [] -> True
 x1 : x2 : [] -> x1 == x2
 x1 : xs -> x1 == last xs && isPalindrome (init xs)
  • 14. Refining the Palindrome Pattern matching without case isPalindrome :: String -> Bool
 isPalindrome [] = True
 isPalindrome (x : []) = True
 isPalindrome (x1 : x2 : []) = x1 == x2
 isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
  • 15. List Type and Pattern Match ghci> :info [] data [] a = [] | a : [a] -- Defined in ‘GHC.Types’ ghci> 1 : 2 : 3 : [] [1,2,3] ghci> [1,2,3] [1,2,3] 1 2 3 []
  • 16. Refining the Palindrome Is whatever a palindrome? isPalindrome :: (Eq a) => [a] -> Bool
 isPalindrome [] = True
 isPalindrome (x : []) = True
 isPalindrome (x1 : x2 : []) = x1 == x2
 isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs) ghci> isPalindrome [1,2,3] False ghci> isPalindrome [1,2,1] True
  • 17. Why the (Eq a) => ? Type Classes ghci> :info Eq class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool
  • 18. ghci> :l HaskellPlayground.hs [1 of 1] Compiling HaskellPlayground ( HaskellPlayground.hs, interpreted ) HaskellPlayground.hs:35:31: error: • No instance for (Eq a) arising from a use of ‘==’ Possible fix: add (Eq a) to the context of the type signature for: isPalindrome :: [a] -> Bool isPalindrome :: [a] -> Bool isPalindrome :: (Eq a) => [a] -> Bool
 isPalindrome [] = True
 isPalindrome (x : []) = True
 isPalindrome (x1 : x2 : []) = x1 == x2
 isPalindrome (x1 : xs) = x1 == last xs && isPalindrome (init xs)
  • 19. I want to call isPalindrome on my own Type data Book =
 Single String
 | Trilogy String
 | Series String
 deriving (Show) data Book =
 Single { title :: String }
 | Trilogy { title :: String }
 | Series { title :: String }
 deriving (Show) ghci> let b = Trilogy {title = "Lord of the Rings"} ghci> b Trilogy {title = "Lord of the Rings”} ghci> title b "Lord of the Rings" ghci> let b2 = b {title = "Lord of the Rings Version 2"} ghci> b2 Trilogy {title = "Lord of the Rings Version 2"} ghci> b Trilogy {title = "Lord of the Rings"}
  • 20. Is my book list a palindrome? ghci> isPalindrome [(Single "The Hobbit"), (Trilogy "Lord of the Rings"), (Single "The Hobbit")] <interactive>:22:1: error: • No instance for (Eq Book) arising from a use of ‘isPalindrome’
  • 21. Comparing my books instance Eq Book where
 (==) (Single t1) (Single t2) = t1 == t2
 (==) (Trilogy t1) (Trilogy t2) = t1 == t2
 (==) (Series t1) (Series t2) = t1 == t2
 (==) _ _ = False ghci> :info Eq class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool
  • 22. ghci> isPalindrome [(Single "The Hobbit"), (Trilogy "Lord of the Rings"), (Single "The Hobbit")] True ghci> isPalindrome [(Single "The Hobbit"), (Trilogy "Lord of the Rings"), (Series "The Hobbit")] False Now are my books a palindrome?
  • 23. Derving Type Classes data Book =
 Single String
 | Trilogy String
 | Series String
 deriving (Show, Eq) ghci> :info Show class Show a where …. show :: a -> String ….
  • 24. Are they all palindromes? ["racecar","wow","huzzah"] allPalindromes = areAllPalindromes [
 [(Single "S"), (Trilogy "T"), (Single "S")],
 [(Series "S"), (Trilogy "T"), (Series "S")]
 ] allPalindromes = areAllPalindromes [
 [(Single "S"), (Trilogy "T"), (Single "S")],
 [(Series "S"), (Trilogy "T"), (Series "S2")]
 ]
  • 25. Are they all palindromes? Almost imperative style loop areAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes listOfLists =
 loop listOfLists where
 loop lOfl =
 case lOfl of
 [] -> True
 (x : xs) -> isPalindrome x && loop xs ghci> areAllPalindromes ["racecar", "wow", "huzzuh"] True ghci> areAllPalindromes ["racecar", "wow", "huzzah"] False
  • 26. Are they all palindromes? Refining the recursion areAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes [] = True
 areAllPalindromes (x : xs) = isPalindrome x && areAllPalindromes xs
  • 27. Are they all palindromes? FoldareAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes lOfLs =
 foldr (x result -> isPalindrome x && result) True lOfLs ["racecar", "wow", "huzzah"] reduces as follows: (isPalindrome "racecar") True && ((isPalindrome "wow") True && ((isPalindrome “huzzah") False && True)))
  • 28. Point Free Niceness ! palindromeWithAnding :: (Eq a) => [a] -> Bool -> Bool
 palindromeWithAnding x b = (&&) (isPalindrome x) b ghci> palindromeWithAnding "huzzuh" False False ghci> palindromeWithAnding "huzzuh" True True Function by Name Binding.. areAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes lOfLs = foldr palindromeWithAnding True lOfLs
  • 29. Map and then Fold ghci> map isPalindrome ["racecar", "wow", “huzzah"] [True,True,False] areAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes lOfLs = foldr (x result -> x && result) True (map isPalindrome lOfLs) WITH POINT FREE && areAllPalindromes :: (Eq a) => [[a]] -> Bool
 areAllPalindromes lOfLs = foldr (&&) True (map isPalindrome lOfLs)
  • 30. Automatic Currying Niceness !map isPalindrome lOfLs ghci> :t map map :: (a -> b) -> [a] -> [b] So.. map func list pseudocode map = func -> list -> ‘map this list with func function’ map isPalindrome list -> ‘map this list with isPalindrome function’
  • 31. areAllPalindromes lOfLs = (foldr (&&) True) (map isPalindrome lOfLs) map and then fold fold . map areAllPalindromes lOfLs = (foldr (&&) True) . (map isPalindrome) $ lOfLs areAllPalindromes = (foldr (&&) True) . (map isPalindrome) areAllPalindromes = foldr (&&) True . map isPalindrome Function Composition Niceness !
  • 32. Composition and Point Free Pipeline Declaration Focusing on Transformations Map with isPalindrome Fold with && ["racecar", "wow", "huzzuh"] [True, True, True] True
  • 33. onlyPalindromes :: (Eq a) => [[a]] -> [[a]]
 onlyPalindromes xs = filter isPalindrome xs ghci> onlyPalindromes ["racecar", "huzzah", "wow"] [“racecar","wow"] USING AUTOMATIC CURRYING onlyPalindromes :: (Eq a) => [[a]] -> [[a]]
 onlyPalindromes = filter isPalindrome Filter Palindromes
  • 34. Haskell Laziness ghci> length ["racecar", "huzzah", undefined] 3 ghci> length (map head ["racecar", "huzzah", undefined]) 3 ghci> take 2 (map head ["racecar", "huzzah", undefined]) “rh" ghci> take 3 (map head ["racecar", "huzzah", undefined]) "rh*** Exception: Prelude.undefined ghci> take 1 (filter isPalindrome ["racecar", "huzzah", undefined]) [“racecar"] ghci> take 2 (filter isPalindrome ["racecar", "huzzah", undefined]) ["racecar"*** Exception: Prelude.undefined
  • 35. How do I get started https://www.haskell.org/platform/ Start a REPL with ➜ ~ ghci GHCi, version 8.0.1: http://www.haskell.org/ghc/ :? for help Loaded GHCi configuration from /Users/tom/.ghci ghci> Play with the examples from this talk GitHub priort