I'd like to define a function, safeIndex that works on Foldable types
safeIndex :: (Foldable t, Integral i) => t a -> i -> Maybe a
safeIndex = foldr step (const Nothing)
where
step :: Integral i => a -> (i -> Maybe a) -> i -> Maybe a
step x f i = if i == 0
then Just x
else f (i - 1)
But it doesn't work for infinite lists. For foldr to stop in the middle, I think we have to determine whether it should stop only with the first argument of step, which seems impossible.
Is it possible to fix the function so that it works on infinite structures? If not, what typeclasses should we restrict t to?
Actually the definition in the question description already works for infinite built-in list. It was some other mistakes that make me thought it couldn't ;) (See the comments.)