diff options
author | Edoardo La Greca | 2025-07-03 20:54:46 +0200 |
---|---|---|
committer | Edoardo La Greca | 2025-07-03 20:54:46 +0200 |
commit | 23a4d27e4f331abc31bee3e2bc418fc9ceb3ec21 (patch) | |
tree | 5421ff7f98a19df0a17719fc1c62621f6f48e3c6 /lec03/Golf.hs | |
parent | 08ef4a40c204410270b1fc907c1cd3727085e707 (diff) |
shorten first exercise solution
Diffstat (limited to 'lec03/Golf.hs')
-rw-r--r-- | lec03/Golf.hs | 33 |
1 files changed, 15 insertions, 18 deletions
diff --git a/lec03/Golf.hs b/lec03/Golf.hs index eb69136..b89aa57 100644 --- a/lec03/Golf.hs +++ b/lec03/Golf.hs @@ -3,25 +3,22 @@ module Golf where -- Exercise 1 -- Explanation: --- takeEvery takes all elements with index equal or multiple of a given --- positive number, index 0 exluded. In the first two cases, it checks whether --- the list is empty or the number is zero, and returns an empty list if so. In --- the next case, which is the most general, it defines l2 and l3, which are --- respectively the list without the first n-1 and n elements. Then it takes --- the fist element out of l2, which, relative to the list, has an index --- multiple of (or equal to) the given number, and then recursively call the --- function itself on l3 so that it drops another (n-1) elements and takes the --- one whose index is multiple of the number, etc. -takeEvery :: [a] -> Int -> [a] -takeEvery [] _ = [] -takeEvery _ 0 = [] -takeEvery l n = take 1 l2 ++ takeEvery l3 n - where - l2 = drop (n-1) l - l3 = drop 1 l2 +-- 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 calls takeEvery for every number from 1 to the length of the list - 1. +-- 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 (takeEvery l) [1..length l] +skips l = map (\n -> concatMap (takeNth l . (*n)) nl) nl + where + len = length l + nl = [1..len] |