What is the method of adding every 5th (or nth) element of a list?

Viewed 89

I have been trying to work off an example provided from this question on StackOverflow. I'm misinterpreting it though. I want to strip every 5th element from the list and put them in another list together.

Here is my best attempt at it so far.

fifth(_:_:_:_xs) = xs fifth xs
fifth [] = []
1 Answers

It is probably better to separate your concerns: make a function that "slices" the list and takes every fifth element, and then sum that list.

fifth :: [a] -> [a]
fifth (x:_:_:_:_:xs) = x : fifth xs
fifth (x:_) = [x]
fifth [] = []

then you sum the list of elements with:

sumFifth :: Num a => [a] -> a
sumFifth = sum . fifth
Related