Add a safe index to Data.Foldable
Data.Foldable has no easy way to do indexing at all, and the libraries lack an easy way to do safe indexing even on [].
I therefore propose that a safe index operator be added to base; something like the following:
(!!?) :: Data.Foldable.Foldable f => f a -> Int -> Maybe a f !!? i = either Just (const Nothing) $
Data.Foldable.foldl (\a v -> a >>=
\idx -> if idx == 0 then Left v else Right (idx - 1))
(Right i) f
safeIndex = (!!?)
Usage example:
map ([1,2,3]!!?) [0..10]
[Just 1,Just 2,Just 3,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing]
Trac metadata
Trac field | Value |
---|---|
Version | 7.2.1 |
Type | FeatureRequest |
TypeOfFailure | OtherFailure |
Priority | normal |
Resolution | Unresolved |
Component | libraries/base |
Test case | |
Differential revisions | |
BlockedBy | |
Related | |
Blocking | |
CC | |
Operating system | |
Architecture |