Week 35 Flashcards

1
Q

Simple functions

How is a function defined in Haskell?

A

name of the function + variable + the function in it self

sq x = x * x

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Simple functions

What does the program do when running bar(bar3)?

A

First it runs the bar function with the varaible 3. Then it runs the bar function again but with bar(3) as a varaible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Bool

How can you use the if and else statments in Haskell?

A

doubleSmallNumber x = if x > 100
then x
else x * 2

The “else” part is mandatory, every expresion needs a value in Haskell

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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

A

price :: Double -> Double

priceKg x =
| 50 < x > 100 = x * 270 * 0.8
| x > 100 = x * 270 * 0.7
| otherwise = x * 270

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Pattern Matching

What is pattern matching?

A

Specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Pattern Matching

There is 4 major types of pattern matching used in Haskell, what are they?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Logic

What logical operators are used in Haskell and what do they mean

A

ghci>True && True (and)
True

ghci> False || True (or)
True

ghci> not False
True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Logic

What operators are used to test form equalitys in Haskell?

A

ghci> 5 == 5 (is equall to)
True

ghci> 5 /= 5 (is greater than )
False

ghci> 5 =/ 5 (is less than)
False

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Values

What functions are used to get the ma or min of a number of arguments?

A

ghci> min 9 10
9

ghci> max 100 101
101

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Values

What function are used to get the next variable for inputs that can be ranked?

A

ghci> succ 9
10

ghci> succ a
b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Values

What function are used to calculate modules?

A

ghci> 4 ´mod´ 2
2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Values

What function is used to divide 2 arguments?

A

ghci> 6 ´div´2
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Values

What function converts a type to a integral

A

fromIntegral :: (Num b, Integral a) => a -> b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Recursion

What is recursion in haskell?

A

A way of defining functions in which the function is applied inside its own definition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Recursion

Write a program which calulates the power of a exponent?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Write a program for factorial numbers

A

fac 0 = 1
fac n = n * fac (n-1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Recursion

Write a program for the fibbonacci sequence

A

fib
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Recursion

Write a program which reverses a list

A

reverse’ :: [a] -> [a]
reverse’ [] = []
reverse’ (x:xs) = reverse’ xs ++ [x]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Lists

What is a list in Haskell?

A

Lists stores several elements of the SAME type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Lists

Write 3 lists; the first is an empty list, the second is a empty list within another list

A

[] (empty list)

[ [] ] (a list containg an empty list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

List

What are strings?

A

Strings are lists of characters
“hello” = [’h’,’e’,’l’,’l’,’o’]

List functions works on strings aswell

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

List - functions

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

List - functions

What function is used to add lists together?

A

ghci>[ ’w’,’o’] ++ [’o’,’t’]
“woot”

24
# List - functions What function is used to add a element in the beginning of a list?
ghci> **’A’ : **"SMALL CAT" "A SMALL CAT"
25
# 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
26
# 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
27
# Lists - functions What function returns the first element in a list?
ghci> **head** [5,4,3,2,1] 5
28
# Lists - functions What function returns the last element in a list?
ghci> **tail** [5,4,3,2,1] 1
29
# Lists - functions What function returns the lenght of the list?
ghci> **lenght** [5,4,3,2,1] 5
30
# Lists - functions What function checks if a list is empty?
ghci> **null** [1,2,3] False
31
# Lists - functions What function reveses a list?
ghci>** reverse **[5,4,3,2,1] [1,2,3,4,5]
32
# Lists - functins What function takes out elements from the beginning of a list?
ghci> **take** 3 [5,4,3,2,1] [5,4,3]
33
# Lists - functions What function drops elements in a list from the beginnig?
ghci> **drop** 3 [5,4,3,2,1] [2,1]
34
# Lists - functions What function checks if something is a element in the list?
ghci> **3 'elem'** [5,4,3,2,1] True
35
# 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]
36
# 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)
37
# Tuples - functions What function is used to access the 1st element in a tuple?
ghci> **fst** (8,11) 8
38
# Tuples - functions What function is used to access the 2nd element in a tuple?
ghci> **snd** (8,11) 11
39
# 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)]
40
# Type classes/variables What does type classes/variables do in Haskell?
They defines a variable’s behaviour and implements the behavior the typeclass describes
41
# Type classes/variables How do you define a type variable in Haskell?
ghci> :t head head :: [a] -> a | a can be of any type
42
# 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
43
# Type classes/variables You can add the deriving keyword 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.
44
# Guards What are Guards in Haskell?
They works as a boolean expression in Haskell. They are useful when working with recursion.
45
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
46
# 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]
47
# Datatype defintions What is datatype defintions in Haskell?
It's a way of defining your own types in Haskell
48
# Datatype definitions Write a datatype definitions for suits in a deck of cards
data Suit = Hearts | Diamonds | Clubs | Spades deriving (Eq, Show)
49
# 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
50
# 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
51
# 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)
52
# 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]
53
# 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
54
# 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
55
# 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]