infinite lists Flashcards
Fibonacci of n
fib::Int->Int
fib::Int->Int
fib 0 = 0
fib 1 = 1
fib n = (fib n-2) + (fib n-1)
quicksort
qsort::Ord a => [a] -> [a]
qsort::Ord a => [a] -> [a] qsort [] = [] qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger where smaller = [a | a ← xs, a <= x] larger = [b | b ← xs, b > x]
reverse
reverse::[a] -> [a]
reverse::[a] -> [a]
reverse [] = []
reverse (x:xs) = reverse xs ++ [x]
or
reverse = foldr (\x xs -> xs ++ [x]) []
find (dictonary)
find::Eq a => a -> [(a,b)] -> [b]
find::Eq a => a -> [(a,b)] -> [b]
find k t = [v | (k’,v) ← t, k’ == k]
factors (all factors of a number from 1 to n)
factors:: Int -> [Int]
factors:: Int -> [Int]
factors n = [x | x ← [1..n], n mod
x == 0]
rotate (move n letters from front to back)
rotate:: Int -> String -> String
rotate:: Int -> String -> String
rotate n xs = drop n xs ++ take n xs
factoral
fac::Int -> Int
fac::Int -> Int fac n = product [1..n] or fac 0 = 1 fac n = n * fac (n-1)
(*) (defined recursively with +)
(*):: Int -> Int -> Int
(*):: Int -> Int -> Int
m * 0 = 0
m * n = m + (m * (n-1))
product (multiply all items in list)
product::Num a => [a] -> a
product::Num a => [a] -> a
product [] = []
product (n:ns) = n * product ns
or
product = foldr (*) 1
length (of list)
length::[a] -> Int
length::[a] -> Int
length [] = 0
length (_:xs) = 1 + length xs
or
length = foldr (_ n -> 1 + n) 0
(++) append lists
(++):: [a] -> [a] -> [a]
(++):: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
insert (into ordered list)
insert:: Ord a=> a -> [a] -> [a]
insert:: Ord a=> a -> [a] -> [a] insert x [] = [x] insert x (y:ys) | x <= y = x : y : ys | otherwise = y : insert x ys
insert sort (using insert::Ord=> a -> [a] -> [a]) isort:: Ord a => [a] -> [a]
isort:: Ord a => [a] -> [a]
isort [] = []
isort (x:xs) = insert x (isort xs)
zip
zip::[a] -> [b] -> [(a,b)]
zip::[a] -> [b] -> [(a,b)]
zip [] _ = []
zip _ [] = []
zip (x:xs) (y:ys) = (x,y) : zip xs ys
drop (first n of a list)
drop:: Int -> [a] -> [a]
drop:: Int -> [a] -> [a]
drop 0 _ = []
drop _ [] = []
drop n (_:xs) = drop (n-1) xs