Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements by index in haskell

Tags:

list

haskell

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?

like image 871
qba Avatar asked Nov 14 '09 23:11

qba


People also ask

How do you delete an element from an index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output.

How do you remove a specific element from a list in Haskell?

You first compare the head of the list ( y ) to the item you want to remove and correctly return the item or an empty list using areTheySame . Then you want to recursively continue using removeItem on the rest of the list ( ys ). The resulting list needs to be concatenated using ++ .


2 Answers

Here is my take:

deleteAt idx xs = lft ++ rgt
  where (lft, (_:rgt)) = splitAt idx xs
like image 143
user1291661 Avatar answered Sep 19 '22 08:09

user1291661


You can count your elements easily:

strip' (x:xs) n | n == 7 = strip' xs 0
                | n >= 5 = strip' xs (n+1)
                | n < 5 = x : strip' xs (n+1)
strip l = strip' l 0

Though open-coding looks shorter:

strip (a:b:c:d:e:_:_:_:xs) = a:b:c:d:e:strip xs
strip (a:b:c:d:e:xs) = a:b:c:d:e:[]
strip xs = xs
like image 28
dottedmag Avatar answered Sep 21 '22 08:09

dottedmag