Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove every nth element from string

Tags:

haskell

How can you remove every nth element of a string?

I'm guessing you would use the drop function in some kind of way.

Like this drops the first n, how can you change this so only drops the nth, and then the nth after that, and so on, rather than all?

dropthem n xs = drop n xs
like image 401
Lunar Avatar asked Mar 13 '11 11:03

Lunar


People also ask

How do you remove every nth element in Python?

Use list slicing to remove every Nth element from a list, e.g. del my_list[::2] . The value between the square brackets is the step which can be used to remove every Nth element from the list. Copied!

How do you remove every nth element from an array?

Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted. To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.

How to delete every other element in a list Python?

Use the del statement with list slicing to remove every second element from a list, e.g. del my_list[::2] . The del statement will remove every second element from the list starting at the specified start index. Copied!


2 Answers

Simple. Take (n-1) elements, then skip 1, rinse and repeat.

dropEvery _ [] = []
dropEvery n xs = take (n-1) xs ++ dropEvery n (drop n xs)

Or in showS style for efficiency's sake

dropEvery n xs = dropEvery' n xs $ []
    where dropEvery' n [] = id
          dropEvery' n xs = (take (n-1) xs ++) . dropEvery n (drop n xs)
like image 70
Dan Burton Avatar answered Sep 28 '22 03:09

Dan Burton


-- groups is a pretty useful function on its own!
groups :: Int -> [a] -> [[a]]
groups n = map (take n) . takeWhile (not . null) . iterate (drop n)

removeEveryNth :: Int -> [a] -> [a]
removeEveryNth n = concatMap (take (n-1)) . groups n
like image 36
Peaker Avatar answered Sep 28 '22 02:09

Peaker