Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

I tried looking up Int -> [a] -> Maybe a on hoogle, but no luck.

I feel like this should be in a standard library somewhere, but I don't know where.

like image 347
rampion Avatar asked Oct 14 '11 13:10

rampion


2 Answers

There is a library called Safe on Hackage which holds a function:

atMay :: [a] -> Int -> Maybe a
like image 161
frosch03 Avatar answered Oct 17 '22 18:10

frosch03


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)
like image 24
shang Avatar answered Oct 17 '22 17:10

shang