开发者

Haskell: Is there a safe/total version of (!!)?

开发者 https://www.devze.com 2023-04-12 20:33 出处:网络
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 S

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号