How to remove an item from a list by index using a lens library?

I can view, say, the 4th element in the list using this lens:

preview (ix 3) myList

Is there something that can replace “preview” to remove the fourth item from the list instead of viewing it? The return list must match the original list, since the 4th item will be deleted.

Or maybe there might be a way to do this using a filtered function?

+4
source share
2 answers

It looks like you want to use ifiltered:

toListOf (folded . ifiltered (\i _ -> i /= 3)) $ myList

-- or

myList ^.. folded . ifiltered (\i _ -> i /= 3))
+3
source

There is a more general way to do this using Monoidand Foldable.

deleteN
  :: (Foldable f, Monoid (f a))
  => (a -> f a -> f a) -- ^ cons operator
  -> Int -- ^ index to delete
  -> f a -- ^ initial structure
  -> f a -- ^ resultant structure
deleteN cons n xs = flipTfo xs $ folded . ifiltered (\i _ -> i /= n)
  where
    flipTfo = flip toFoldableOf
    toFoldableOf l = foldrOf l cons mempty

deleteList :: Monoid a => Int -> [a] -> [a]
deleteList = deleteN (:)
+2

All Articles