I’m new in haskell and I’m looking for some standard functions to work with lists by indexes.
My exact problem is that i want to remove 3 elements after every 5. If its not clear enough here is illustration:
OOOOOXXXOOOOOXXX...
I know how to write huge function with many parameters, but is there any clever way to do this?
Two completely different approaches
You can use
List.splitAttogether withdrop:Now
f [1..12]yields[1,2,3,4,5,9,10,11,12]. Note that this function can be expressed more elegantly usinguncurryandControl.Arrow.second:Since we’re using
Control.Arrowanyway, we can opt to dropsplitAtand instead call in the help ofControl.Arrow.(&&&), combined withtake:But now it’s clear that an even shorter solution is the following:
As Chris Lutz notes, this solution can then be generalized as follows:
Now
nofm 5 8yields the required function. Note that a solution withsplitAtmay still be more efficient!Apply some mathematics using
map,snd,filter,modandzip:The idea here is that we pair each element in the list with its index, a natural number i. We then remove those elements for which i % 8 > 4. The general version of this solution is: