SlideShare a Scribd company logo
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 haskell
Jongsoo 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 Haskell
Functional Thursday
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
Hackraft
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
Muthu Vinayagam
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
Roberto Pepato
 
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
Jason 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 World
osfameron
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
Aleksandras Smirnovas
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
Knoldus 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 World
Bryan O'Sullivan
 
Functional data structures
Functional data structuresFunctional data structures
Functional data structures
Ralf 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 - 4Developers
Sam 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 Workflows
Paco Nathan
 
Reactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons LearnedReactive Programming With Akka - Lessons Learned
Reactive Programming With Akka - Lessons Learned
Daniel 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 Framework
Adam 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 Akka
drewhk
 
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
 
Efficient HTTP Apis
Efficient HTTP ApisEfficient HTTP Apis
Efficient HTTP Apis
Adrian Cole
 
Haskell
HaskellHaskell
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 JavaScript
Will Kurt
 
Building ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudBuilding ‘Bootiful’ microservices cloud
Building ‘Bootiful’ microservices cloudIdan Fridman
 
Effective Actors
Effective ActorsEffective Actors
Effective Actors
shinolajla
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
Bikram Thapa
 
Curator intro
Curator introCurator intro
Curator intro
Jordan Zimmerman
 
Using Apache Solr
Using Apache SolrUsing Apache Solr
Using Apache Solr
pittaya
 
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 Haskell
Hiromi 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 212
Mahmoud Samir Fayed
 
XKE Typeclass
XKE TypeclassXKE Typeclass
XKE Typeclass
Mathieu DULAC
 
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 181
Mahmoud Samir Fayed
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Music as data
Music as dataMusic as data
Music as data
John Vlachoyiannis
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
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 Scala
Skills 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 Cats
Philip 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 202
Mahmoud Samir Fayed
 
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
Mahmoud 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

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
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
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
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
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
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
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
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
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
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
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 

Recently uploaded (20)

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
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
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
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...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
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
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
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
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
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
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

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