purescript-arrays icon indicating copy to clipboard operation
purescript-arrays copied to clipboard

deleteWith function & friends

Open flip111 opened this issue 1 year ago • 2 comments

A lot of functions like delete require an index. A lot of times that index was not stored (which would also get updated as the array would change) but has to be refound with findIndex. When you use findIndex and immediately after use delete you know you are guaranteed an index that is not out of bounds. Could "with" functions be added that do this?

deleteWith :: forall a. (a -> Boolean) -> Array a -> Maybe (Array a)
deleteWith pred array = map (\idx -> unsafeDeleteAt idx array) (findIndex pred array)

It would make sense to have the unsafe implementations for them available, at least internally in the array library https://github.com/purescript/purescript-arrays/issues/167

One could argue that if you do this you are better off using a Map. But i think people will want to use an array plenty of times anyway.

flip111 avatar Sep 01 '23 21:09 flip111

At first I was going to suggest that this seems like a worse filter, but the difference is it's intended to only delete the first instance of the value matching the predicate? And return Nothing if nothing matched?

garyb avatar Sep 01 '23 22:09 garyb

yes

flip111 avatar Sep 02 '23 11:09 flip111