Haskell: Is there a safe/total version of (!!)?
I tried looking up Int -> [a] -> Maybe a
on hoogle, but no luck.
I feel like this should be in a stan开发者_Python百科dard library somewhere, but I don't know where.
There is a library called Safe on Hackage which holds a function:
atMay :: [a] -> Int -> Maybe a
There isn't one in the standard library (would be nice, though), but here's one way to implement it (also works for infinite lists):
(!!!) :: [a] -> Int -> Maybe a
[] !!! _ = Nothing
(x:xs) !!! n
| n < 0 = Nothing
| n == 0 = Just x
| otherwise = xs !!! (n-1)
A possible definition for such a function (mostly stolen from the definition of (!!)
):
xs !!! n | n < 0 = Nothing
[] !!! _ = Nothing
(x:_) !!! 0 = Just x
(_:xs) !!! n = xs !!! (n-1)
How about
(!!!) :: [a] -> Int -> Maybe a
xs !!! n = Maybe.listToMaybe $ drop n xs
精彩评论