[GHC] #5758: Add a safe index to Data.Foldable

GHC cvs-ghc at haskell.org
Tue Jan 10 00:20:30 CET 2012


#5758: Add a safe index to Data.Foldable
------------------------------+---------------------------------------------
 Reporter:  A1kmm             |          Owner:                  
     Type:  feature request   |         Status:  new             
 Priority:  normal            |      Component:  libraries/base  
  Version:  7.2.1             |       Keywords:                  
       Os:  Unknown/Multiple  |   Architecture:  Unknown/Multiple
  Failure:  None/Unknown      |       Testcase:                  
Blockedby:                    |       Blocking:                  
  Related:                    |  
------------------------------+---------------------------------------------
 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]

-- 
Ticket URL: <http://hackage.haskell.org/trac/ghc/ticket/5758>
GHC <http://www.haskell.org/ghc/>
The Glasgow Haskell Compiler



More information about the Glasgow-haskell-bugs mailing list