ndmitchell / extra

Extra Haskell functions
Other
93 stars 37 forks source link

selectIndices #107

Open sullyj3 opened 1 year ago

sullyj3 commented 1 year ago

I find myself constantly re-implementing this function:

-- | given a list of indices and a list, return the elements at those indices
-- Assumes indices are sorted. If indices that are out of bounds are given,
-- they are silently ignored.
selectIndices :: [Int] -> [a] -> [a]
selectIndices indices list = go indices list 0
  where
    go [] _ _ = []
    go _ [] _ = []
    go (index:indices) (x:xs) currentIndex
      | index == currentIndex = x : go indices xs (currentIndex + 1)
      | otherwise = go (index:indices) xs (currentIndex + 1)

Would you accept a PR for this?

ndmitchell commented 10 months ago

I really worry about the requirement for indices to be sorted - if you don't have that, it can't operate lazily, if you do have that, there is an easy to make mistake that is really hard to find. I don't really know a way to fix this API.

sullyj3 commented 10 months ago

fair point