blob: e4fa9a3c19a37e29b3030da9f79b31bdbe830a2a (
plain)
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
|
module Golf where
-- Exercise 1
-- Explanation:
-- takeNth takes the nth value of a list without crashing. First, it drops all
-- the first `n - 1` elements from the list. Then, it takes the desired element.
-- This function is total and can be thought of as the total version of the
-- partial function `!!`.
takeNth :: [a] -> Int -> [a]
takeNth l n = take 1 $ drop (n-1) l
-- Explanation:
-- skips first maps all values in `nl`, defined as all values from 1 to the
-- length of the list (excluded), to `concatMap`, which is the same as `concat
-- (map ...)`. `concatMap` maps again the same array, this time multiplied by
-- each value `n` coming from the outer map, to takeNth of the given list `l`
-- and concatenates the result.
skips :: [a] -> [[a]]
skips [] = []
skips l = map (\n -> concatMap (takeNth l . (*n)) nl) nl
where
len = length l
nl = [1..len]
-- Exercise 2
-- Explanation:
-- localMaxima is defined in two cases. In the first case, the argument of the
-- function is a list with at least 3 elments. Depending on the value of the
-- first three elements, checked through two guards, the second is either
-- included or excluded from the resulting list. In particular, the first guard
-- checks whether both the first and the third are smaller than the second using
-- the `all` function. The second case matches if the list has less than 3
-- elements, in which case the result is just an empty list.
-- The list resulting from the `localMaxima` function is built recursively.
localMaxima :: [Integer] -> [Integer]
localMaxima (x1:x2:x3:xs)
| all (<x2) [x1,x3] = x2 : localMaxima (x2:x3:xs)
| otherwise = localMaxima (x2:x3:xs)
localMaxima l = []
|