Haskell Flashcards
What is a functor?
A functor is a container which provides a function fmap which allows us to transform its values using a function, while keeping the structure of the container the same.
Defining a functor instance for a data type
If the data type declaration is
“data TypeName a = Fizz a | Buzz (TypeName a) a”
The functor instance is
instance Functor TypeName where
fmap f (Fizz a) = Fizz (f a)
fmap f (Buzz b a) = TypeName (fmap f b) (f a)
Defining a functor instance for the data type “data Tree a = Leaf a | Node (Tree a) a (Tree a) (Tree a)”
instance Functor Tree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Node left a mid right) = Node (fmap f left) (f a) (fmap f mid) (fmap f right)
What do tail and init do, and what is their syntax?
tail [1, 2, 3, 4, 5] = [2, 3, 4, 5]
init [1, 2, 3, 4, 5] = [1, 2, 3, 4]
What does zip do?
It turns a pair of lists into a list of pairs, up until the length of the shorter pair
Example:
zip [1, 2, 3, 4] [5, 6, 7] = [(1,5),(2,6),(3,7)]
What does zipWith do?
zipWith (op) a b
zips the lists a and b, and then performs the operation on each pair
Concatenating two lists
Use the ++ operator
Example: map (y*) x ++ mymult x ys
Example of patterns in function definition
mymult x [] = []
mymult x (y:ys) = map (y*) x ++ mymult x ys
Using zipWith to work out the differences between consecutive numbers in a list
zipWith (-) vge (tail vge))
Calculates A_i - A_i+1
Using length to calculate the number of items in myList which satisfy “condition”
length [x | x <- myList, condition]
Haskell if statement syntax
if <condition>
then <action>
else <action></action></action></condition>
if var rem
2 == 0
then putStrLn “Even”
else putStrLn “Odd”
Syntax for writing a function definition with multiple cases
functionName <pattern>
| <condition> = <value>
| <condition> = <value>
| otherwise = <value></value></value></condition></value></condition></pattern>
partitionHelper (x:xs) n (y:ys)
| sameSign n x == True = partitionHelper xs x ((x:y):ys)
| sameSign n x == False = partitionHelper xs x ([x]:y:ys)
AND, OR, NOT, not equal operators
AND = &&
OR = ||
NOT = not (e.g. (not True) = False)
not equal = =
Prepending an item to a list
Use the “:” operator
1 : [2, 3, 4] = [1, 2, 3, 4]
What is lambda calculus?
Rule system for describing computations solely via function abstraction and application. It’s the simplest known Turing-complete programming language.