Week 35 Flashcards
Simple functions
How is a function defined in Haskell?
name of the function + variable + the function in it self
sq x = x * x
Simple functions
What does the program do when running bar(bar3)?
First it runs the bar function with the varaible 3. Then it runs the bar function again but with bar(3) as a varaible.
Bool
How can you use the if and else statments in Haskell?
doubleSmallNumber x = if x > 100
then x
else x * 2
The “else” part is mandatory, every expresion needs a value in Haskell
Bool
Solve:
The price of prawns: 270/Kg. Define a function price to calculate the cost of a given weight of prawns. Suppose price gets cheaper if we buy more: unit price/Kg up to 50 kg, and a discount of 20% per Kg for everything above 50kg, plus an additional 10% above 100 kg
price :: Double -> Double
priceKg x =
| 50 < x > 100 = x * 270 * 0.8
| x > 100 = x * 270 * 0.7
| otherwise = x * 270
Pattern Matching
What is pattern matching?
Specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns
Pattern Matching
There is 4 major types of pattern matching used in Haskell, what are they?
fmatchesanything at all, and binds thefvariable to whatever is matched
(x:xs)imatches anon-empty listwhich is formed by something (which gets bound to thexvariable) onto something else (which gets bound toxs).
[]is a pattern that matchesthe empty list. It doesn’t bind any variables.
**_ **is the pattern which matches anything without binding
Logic
What logical operators are used in Haskell and what do they mean
ghci>True && True (and)
True
ghci> False || True (or)
True
ghci> not False
True
Logic
What operators are used to test form equalitys in Haskell?
ghci> 5 == 5 (is equall to)
True
ghci> 5 /= 5 (is greater than )
False
ghci> 5 =/ 5 (is less than)
False
Values
What functions are used to get the ma or min of a number of arguments?
ghci> min 9 10
9
ghci> max 100 101
101
Values
What function are used to get the next variable for inputs that can be ranked?
ghci> succ 9
10
ghci> succ a
b
Values
What function are used to calculate modules?
ghci> 4 ´mod´ 2
2
Values
What function is used to divide 2 arguments?
ghci> 6 ´div´2
3
Values
What function converts a type to a integral
fromIntegral :: (Num b, Integral a) => a -> b
Recursion
What is recursion in haskell?
A way of defining functions in which the function is applied inside its own definition.
Recursion
Write a program which calulates the power of a exponent?
power n k | k < 0 = error “Negative exponent.”
power n 0 = 1
power n k = power n (k-1) * n
power is the name of the function
n and k is the functions’ arguments
th
Write a program for factorial numbers
fac 0 = 1
fac n = n * fac (n-1)
Recursion
Write a program for the fibbonacci sequence
fib
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
Recursion
Write a program which reverses a list
reverse’ :: [a] -> [a]
reverse’ [] = []
reverse’ (x:xs) = reverse’ xs ++ [x]
Lists
What is a list in Haskell?
Lists stores several elements of the SAME type
Lists
Write 3 lists; the first is an empty list, the second is a empty list within another list
[] (empty list)
[ [] ] (a list containg an empty list)
List
What are strings?
Strings are lists of characters
“hello” = [’h’,’e’,’l’,’l’,’o’]
List functions works on strings aswell
List - functions
List - functions
What function is used to add lists together?
ghci>[ ’w’,’o’] ++ [’o’,’t’]
“woot”
List - functions
What function is used to add a element in the beginning of a list?
ghci> **’A’ : **“SMALL CAT”
“A SMALL CAT”
List - functions
What function is used to distract a element from a list?
ghci> “Steve Buscemi”** !! 6**
’B’
Begins counting from the start from begining and it starts with 0
List - functions
What functions is used to compare elements in a list?
< (smaller than)
<= (smaller/equal to)
> (larger than)
> = (larger/equal to)
The first elements are compared, if the match it moves on to the second
Lists - functions
What function returns the first element in a list?
ghci> head [5,4,3,2,1]
5
Lists - functions
What function returns the last element in a list?
ghci> tail [5,4,3,2,1]
1
Lists - functions
What function returns the lenght of the list?
ghci> lenght [5,4,3,2,1]
5
Lists - functions
What function checks if a list is empty?
ghci> null [1,2,3]
False
Lists - functions
What function reveses a list?
ghci>** reverse **[5,4,3,2,1]
[1,2,3,4,5]
Lists - functins
What function takes out elements from the beginning of a list?
ghci> take 3 [5,4,3,2,1]
[5,4,3]
Lists - functions
What function drops elements in a list from the beginnig?
ghci> drop 3 [5,4,3,2,1]
[2,1]
Lists - functions
What function checks if something is a element in the list?
ghci> 3 ‘elem’ [5,4,3,2,1]
True
List comprehnsions
What is list comprehenisions and how is it used in Haskell?
List comprehensions are a more compat way to define a intervall and terms for the functions’ arguments.
ghci> [ x * 2 | x <- [1..10] ]
[2,4,6,8,10,12,14,16,18,20]
Tuples
What is tuples in Haskell?
Stores several values into a single value → elements don’t have to be the same type
tup :: (String, Int)
tup = (“alex”, 1234)
Tuples - functions
What function is used to access the 1st element in a tuple?
ghci> fst (8,11)
8
Tuples - functions
What function is used to access the 2nd element in a tuple?
ghci> snd (8,11)
11
Tuple - functions
What function is used to produce tuples from 2 seperate lists?
ghic> zio [1,2,3,4,5] [5,5,5,5,5]
[(1,5),(2,5),(3,5),(4,5),(5,5)]
Type classes/variables
What does type classes/variables do in Haskell?
They defines a variable’s behaviour and implements the behavior the typeclass describes
Type classes/variables
How do you define a type variable in Haskell?
ghci> :t head
head :: [a] -> a
a can be of any type
Type classes/variables
How do you define a type class in Haskell?
ghci> :t(==)
(==):: (Eq a) => a-> a -> Bool
Everything before the => symbol is called a class constraint
Type classes/variables
You can add thederivingkeyword and a tuple of type classes you want. This could be done by the function (Show, Eq). What does the function do?
It makes the compiler try to figure out the instances for you and choose the best type for the arguments in teh function.
Guards
What are Guards in Haskell?
They works as a boolean expression in Haskell. They are useful when working with recursion.
How is guards used in Haskell?
- If the expression is True → the corresponding function body is used
- If the expression is False → the check drops down to the next guard, if that is true it’s printed
- otherwise —> otherwise =True and catches everything else
Prime functions
Write a program which calcuates prime numbers?
isFactorOf :: Int -> Int -> Bool
isFactorOf x y = y mod
x == 0
factors :: Int -> [Int]
factors n = [x | x <- [1..n], x isFactorOf
n]
isPrime :: Int -> Bool
isPrime x = factors x == [1, x]
primes :: [Int]
primes = [x | x <- [2..], isPrime x]
Datatype defintions
What is datatype defintions in Haskell?
It’s a way of defining your own types in Haskell
Datatype definitions
Write a datatype definitions for suits in a deck of cards
data Suit = Hearts | Diamonds | Clubs | Spades
deriving (Eq, Show)
Exercises week 2
Define the function maxi, which takes two arguments and returns the maximum of the two. (We call this function maxi, because there is a standard function max which does the same thing. Of course, you should not use it.)
Begin by writing a type signature for maxi, and a left hand side “equal to undefined”. Before you write the definition, think of at least one property that you will use for testing your code. You will need to consider two cases: what are they? Write the left hand sides, and make sure GHCi accepts them.
maxi :: Ord a => a -> a -> a
maxi x y
| x>=y = x
| otherwise = y
– | maxi x y returns either x or y
prop_maxi1 :: Int -> Int -> Bool
prop_maxi1 x y = maxi x y == x || maxi x y == y
– | maxi x y returns a value that is greater than or equal to both x and y
prop_maxi2 :: Int -> Int -> Bool
prop_maxi2 x y = maxi x y >= x && maxi x y >= y
Exercises week 2
The price of prawns: 270/Kg. Define a function price to calculate the cost of a given weight of prawns. Moreover, suppose price gets cheaper if we buy more: unit price/Kg up to 50 kg, and a discount of 20% per Kg for everything above 50kg, plus an additional 10% above 100 kg.
price :: Double -> Double
price kg = 270 * kg
priceDiscount :: Double -> Double
priceDiscount kg
| kg > 100 = price (kg - 100) * 0.7 + priceDiscount 100
| kg > 50 = price (kg - 50) * 0.8 + priceDiscount 50
| otherwise = price kg
Exercises week 2
The greatest common divisor (gcd) can be calculated using the Euclidian algorithmLinks to an external site., which works as follows: start with the pair of numbers
and repeatedly replace this by
until the pair is
, where
is the greatest common divisor. For example:
so the gcd of 9 and 6 is 3. Note that the modulo operator (mod) returns the remainder of an integer division. Write a function that returns the greatest common divisor of two given integers:
gcdiv :: Int -> Int -> Int
gcdiv :: (Int, Int) -> Int
gcdiv (x, 0) = x
gcdiv (x, y) = gcdiv (y, x mod
y)
Exercises week 2
Write a function that takes an integer as input calculates all possible casts with two dice that sum upp to the given input:
dice :: Int -> [(Int, Int)]
For example, dice 4 should give [(1,3),(2,2),[(3,1)].
dice :: Int -> [(Int, Int)]
dice n = [(x, y) | x <- [1..6], y <- [1..6], x + y == n]
Exercises week 2
Define a Person data type using record syntax. The Person should store a list of first names, the last name, birth date (as an Int) and the social security number (sv: personnummer). Such a data typ can be modelled as follows using a Haskell data type:
data Person = Person [String] String Int Int
Your task is to define an equivalent data type using record syntax, such as we used to define the Card data type in the lecture about data types.
data Person = Person
{ firstNames :: [String]
, lastName :: String
, birthDate :: Int
, socialSec :: Int
Exercises week 2
Implement a function cardBeats card1 card2 that checks if card1 beats card2:
cardBeats :: Card -> Card -> Bool
This is the case when the two cards have the same suit and card1 has a higher rank as card2. You should implement the function using pattern matching.
data Suit = Spades | Clubs | Hearts | Diamonds deriving (Show, Eq, Enum)
data Rank = Numeric Int | Jack | Queen | King | Ace deriving (Show, Eq, Ord)
data Card = Card
{ rank :: Rank
, suit :: Suit
} deriving Eq
rankBeats :: Rank -> Rank -> Bool
rankBeats x y = x > y
cardBeats :: Card -> Card -> Bool
cardBeats (Card r1 s1) (Card r2 s2) = s1 == s2 && r1 rankBeats
r2
Exercises week 2
Implement a function that selects all the cards from the hand of a given suit:
select :: Suit -> Hand -> [Card]
Use a list comprehension.
type Hand = [Card]
select :: Suit -> Hand -> [Card]
select s hand = [card | card <- hand, suit card == s]