2023/03/17 - 17:09
Tuples:
Examples of tuples:
(True, “hello”) :: (Bool, String)
While python does not care about element types, Haskell is statically typed.
Accessors for pairs:
fst (1 , True)
1
snd (1, True)
True
--these only work for pairs, as described in their method signatures
fst :: (a, b) -> a
fst (x, _) = x
snd :: (a, b) -> b
snd (_, y) = y
type infiniteTuple a = (a, infiniteTuple)
= ( a, (a, (a, (a, ...))))
--this doesnt work
Lists:
Building lists:
- emptyList = []
- oneThroughFour = 1: [2,3,4]
- oneThroughFour = 1: 2: 3: 4: []
Via concatenations:
- oneThroughFive = [1, 2, 3] ++ [4, 5]
- oneThroughFive = concat [[1], [2,3], [], [4, 5]]
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
-- doing this with a constant time list and an infinite list would take constant time, because it would just iterate down the constant time list and then recursively return the second one on the end.
--the end of the first list points to the actual spot in memory where the second list begins.
concat :: [[a]] -> [a]
concat [] = []
concat (x:xs) = x ++ concat xs
Inspecting lists:
Via pattern matching:
second :: [a] -> a
second (_:x:_) = x
second _ = error "List too short!"
index based access:
[1..] !! 100
100
--0 indexed
--potentially slow
(!!)::[a] -> Int -> a
[ ] !! _ = error "List too short"
(x:_) !!.....
null: is this list empty?
returns bool
length: returns length of list
length:: [a] -> Int
length xs = go 0 xs
where
go len [] = len
go len (_:xs) = go (len+1) xs
--tail recursive implementation
last: return last element of a list.
init: the list minus its last element.
^ these take linear time. avoid if possible
you want to add things to the front in haskell, because otherwise getting to the end is a linear time operation.
reverse: returns the list in reverse
reverse :: [a] -> [a]
reverse xs = go [] xs
where
go rev [] = rev
go rev (x:xs) = go (x:rev) xs
map: apply a function to every list element.
filter: the list of elements that match some condition
zip: two lists “side by size”
zip :: [a] -> [b] -> [(a, b)]
zip (x:xs) (y:ys) = (x , y) : zip xs ys
zip _ _ = []
--if either pattern doesn't match, return nothing.
Index