Haskell Course PDF
Haskell Course PDF
1
www.JBarCode.com
About Me
● Started programming in 2005 with C++
● B.S. Electrical Engineering:
○ Minor in Math and Physics
○ Track in Electricity and Magnetism
○ Matlab TA for 3 years
● M.S. Electrical Engineering:
○ Focus in Guidance, Navigation & Control Systems
● Favorite Projects:
○ Building an NFT Launch to Fund Education App (Flutter/Dart, Python)
○ Building an Education App for Android, IOS, and Web (Flutter/Dart, Python, Go?)
○ MTGO Online Trading Bots (C++, SQL)
○ Attitude Determination and Control for a CubeSat (C, Matlab)
○ Auto Pilot & Sensor Integration for Autonomous Vehicles (C, C++, Matlab, Python)
○ Various ML and AI projects
2
About this Course
● #1 Thing: I’m not an expert in Haskell!
○ Terminology and Best Practices will be a little loose at the beginning
○ Learning Haskell to program contracts in Plutus for Cardano (ADA)
○ Teaching Haskell allows me to help others while mastering the material
3
Pre-Reqs (what you Need)
4
How to Support Me (Free to Not-So-Free)
1) Like and Subscribe on YouTube!
a) https://www.youtube.com/JBarCode
2) Follow on Socials:
a) u/JBarCode on Reddit: https://www.reddit.com/user/JBarCode
b) @JBarCode37 on Twitter: https://twitter.com/JBarCode37
5
Last Stream Recap
● We set up a Haskell Programming environment in Linux
● Using Cabal and GHC based on Cardano Node Installation
○ https://docs.cardano.org/projects/cardano-node/en/latest/getting-started/install.html
○ https://www.haskell.org/cabal/download.html
○ https://www.haskell.org/ghc/
● gchi
● *.hs haskell script files
6
Basic Types
● Num:
○ Includes types: Double, Float, Int, Integer, many others
● Float, Double:
○ 0.999, 1.3, -3.2, 0.0, etc.
○ sqrt 99 :: Float, sqrt 99 :: Double
● Int, Integer:
○ -99, 23, 0, 99, 1, 838383, etc.
○ 2^63, 2^63 :: Int, 2^63 :: Integer, 9223372036854775808 :: Int (this gives a warning)
● Char:
○ ‘a’, ‘c’, ‘\t’, ‘\n’, ‘\8371’, etc.
○ Unicode: Try running “putStr ['\t', '\8371', '\n']”
7
Basic Types Cont.
● String or [Char]:
○ "Hello World", ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'], etc.
● Bool:
○ True, False
● Lists:
○ [1, 2, 3], [True, False, True], [“Hello”, “World”], [[0, 0], [0, 4], [5, 0]]
● Tuples:
○ (1, 2, 3), ([1, 2, 3], “Hello World”, 99, True, (“Red”, False)), yikes!
○ Tuples Create Unique Types (hard to write generic functions for them)
8
Numeric Operations (...some of them)
● (+): addition
● (-): subtraction, negate
● (*): multiplication
● (^): exponentiation
● (/): division (Fractional values)
● div: division (integer division, Integral values)
○ div 4 2, div 5 2, 5 `div` 2 (infix notation using backticks)
● reverse:
○ reverse "Hello World", reverse [1, 2, 3, 4, 5]
10
Basic Comparison Operation ( -> Bool)
● (==): Check for Equality
● (/=): Check for inequality
● (>): Greater Than
● (<): Less Than
● (>=): Greater Than or Equal
● (<=): Less Than or Equal
● :info will give you the priority, but it’s often better to use
11
Basic Tuple Operations
● fst: returns the first item of a pair
○ fst (1, 2)
12
List Operations (...some more of them)
● length: gets the length of a list
● (!!): Retrieve a value (index the list):
○ "Hello World" !! 3
13
Basic Logic Operations Bool -> Bool -> Bool
● (&&): And Operator
○ Only True if both left and right inputs are True
○ Lazy evaluation (if the first input is False, it doesn’t check the second input)
● (||): Or Operator
○ Only False if both values are false
○ Lazy evaluation (if the first input is True, it doesn’t check the second input)
14
Revisit List Comprehensions
● Logic Checks
○ [x | x <- [ 1..100], x `mod` 2 == 0]
○ [x | x <- [ 1..100], x `mod` 2 == 0, x < 25]
● Nested List Comprehensions (build a multiplication table)
○ [(x, y, x*y) | x <- [ 1..10], y <- [1..10]]
● When applying a function to a list, it’s often better to use map:
○ map (*2) [1, 2, 3, 4]
○ map (^2) [1, 2, 3, 4]
15
Function Types
● Functions are a Mapping from One Type to Another
● :t not
○ not :: Bool -> Bool
● :t sort
○ sort :: Ord a => [a] -> [a]
○ add3 = add 3
○ add3 5
○ etc.
17
Polymorphic Types
● Must start with lower case as seen in many examples
○ :t head
○ :t map
○ :t length
○ Etc.
18
if statements
● Uses if, then, else format
○ All three parts required
○ if <condition> then <true-value> else <false-value>
20
Function Pattern Matching
● Multiple definitions of a function based on input values
● Priority is from top to bottom
● If no match is found, it will cause an error
○ Try to handle all cases or have a catch all case to handle unexpected values
not' :: Bool -> Bool head' :: [a] -> a fst' :: (a, b) -> a
not' True = False head' [] = error "empty list" fst' (x, _) = x
not' False = True head' (x:_) = x
snd' :: (a, b) -> b
fib :: Int -> Int tail' :: [a] -> [a] snd' (_, x) = x
fib 0 = 0 tail' [] = error "empty list"
fib 1 = 1 tail' (_:xs) = xs
fib n
| n > 0 = fib (n-1) + fib (n-2)
| otherwise = 0
21
Lambda (λ) Expressions
● Anonymous (Nameless) Functions
○ A function has no name
(\x y z -> x + y + z) 1 2 3
22
Operator Sections
● Haskell is pretty smart about applying functions
● Consider:
23
Zip Lists
● Combine values of two list into tuple pairs:
24
ord and chr (import Data.Char)
● ord: Converts Characters to ASCII (Unicode) Value
● chr: Convert ASCII (Unicode) Value to Char
● Ref. http://www.asciitable.com/
ord '4'
ord 'a'
ord 'A'
chr 52
chr 0x61
chr 65
25
Recursion
● Function that is defined using itself
● Function that calls itself
● len, sum, product, fib, and many other examples already seen.
● Standard format is to have initial definitions or exit conditions
length' :: Integral b => [a] -> b product' :: Num a => [a] -> a
length' [] = 0 product' [] = 1
length' (_:xs) = 1 + length' xs product' (x:xs) = x * product' xs
27
Accumulators
● Another approach to sum
● Similar to loop approaches in other languages
● Initialize total to 0 and add each item to the total.
28
Folds
● Built in accumulators
● foldl
○ Left to Right, acc / output can be different type than list items
● foldr
○ Right to Left, acc / output can be different type than list items
● foldl1
○ Left to Right, acc / output is same type as list items. First list item is initial acc value
● foldr1
○ Right to Left, acc / output is same type as list items. First list item is initial acc value
29
Why Monads are Hard
● For Monads, you should know:
○ Monoids. Do you know Monoids well?
○ Applicative Functors. Do you know Applicative Functors well?
○ Functors. Do you know Functors well?
○ Data Structures. Do you know Data Structures well?
○ User Defined Types. Do you know User Defined Types well?
...over the next two weeks we’ll focus on working through this
30
Types
● Use the keyword ‘data’
● Point data type for example:
31