SlideShare a Scribd company logo
1 of 36
Download to read offline
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

More Related Content

What's hot

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...Philip Schwarz
 
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 haskellJongsoo Lee
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
[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 HaskellFunctional Thursday
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1Hackraft
 
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 SwiftJason Larsen
 
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
 
Haskell in the Real World
Haskell in the Real WorldHaskell in the Real World
Haskell in the Real Worldosfameron
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 

What's hot (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
 

Viewers also liked

Haskell for the Real World
Haskell for the Real WorldHaskell for the Real World
Haskell for the Real WorldBryan O'Sullivan
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structuresRalf Laemmel
 
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 - 4DevelopersSam Brannen
 
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 WorkflowsPaco Nathan
 
Reactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons LearnedReactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons LearnedDaniel Sawano
 
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 FrameworkAdam Warski
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingGarth Gilmour
 
Effective akka scalaio
Effective akka scalaioEffective akka scalaio
Effective akka scalaioshinolajla
 
Actor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in AkkaActor Based Asyncronous IO in Akka
Actor Based Asyncronous IO in Akkadrewhk
 
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 2011Adriano Bonat
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP ApisAdrian Cole
 
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 CassandraDataStax
 
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 JavaScriptWill Kurt
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudIdan Fridman
 
Effective Actors
Effective ActorsEffective Actors
Effective Actorsshinolajla
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)Bikram Thapa
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solrpittaya
 
Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)Effective Scala (SoftShake 2013)
Effective Scala (SoftShake 2013)mircodotta
 

Viewers also liked (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 to Beginning Haskell, Dive In, Its Not That Scary!

Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
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 212Mahmoud Samir Fayed
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
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 181Mahmoud Samir Fayed
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
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 CatsPhilip Schwarz
 
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 202Mahmoud Samir Fayed
 
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 210Mahmoud Samir Fayed
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoï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 to 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.
 

Recently uploaded

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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 Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

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