-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lesson4.hs
59 lines (41 loc) · 1.56 KB
/
Lesson4.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- Question 1
-- Lets say you have the nested values defined bellow. How would you get the value of
-- 4 by using only pattern matching in a function?
nested :: [([Int], [Int])]
nested = [([1,2],[3,4]), ([5,6],[7,8])]
three :: [([Int], [Int])] -> Int
three [(_,[_,d]), _] = d
three _ = 0
-- Question 2
-- Write a function that takes a list of elements of any type and, if the list has 3 or more elements, it
-- removes them. Else, it does nothing. Do it two times, one with multiple function definitions and one with
-- case expressions.
elem :: [a] -> [a]
elem n = if length n > 3 then take 3 n else n
remove3 :: [a] -> [a]
remove3 (_:_:_:xs) = xs
remove3 x = x
remove3' :: [a] -> [a]
remove3' list = case list of
(_:_:_:xs) -> xs
x -> x
-- Question 3
-- Create a function that takes a 3-element tuple (all of type Integer) and adds them together
addTuple :: Num a => (a, a, a) -> a
addTuple (x, y, z) = x+y+z
-- Question 4
-- Implement a function that returns True if a list is empty and False otherwise.
isEmpty :: [a] -> Bool
isEmpty = null
-- Question 5
-- Write the implementation of the tail function using pattern matching. But, instead of failing if
-- the list is empty, return an empty list.
tail' :: (Eq a) => [a] -> [a]
tail' [] = []
tail' (x:xs) = xs
-- Question 6
-- write a case expression wrapped in a function that takes an Int and adds one if it's even. Otherwise does nothing.
-- (Use the `even` function to check if the number is even.)
addOne a = case even a of
True -> a + 1
False -> a