I'm currently dealing with some Haskell code that I didn't write, but that I've made changes to. After my changes, I run the program and get the following error message:
Prelude.!!: index too large
The call to !!
is not in my code, so refactoring it away is more work than I want to do, if I can avoid it.
What I'd like is to do something like this:
class PrintList a where
(!!) :: [a] -> Int -> a
instance (Show a) => PrintList a where
l (!!) n = if n < (length l)
then (l Prelude.!! n)
else error ("Index " ++ show n ++ " out of bounds in " ++ show l )
instance PrintList a where
(!!) = Prelude.!!
i.e. the function !!
is defined for every possible list type, but it behaves differently whenever a Show instance is defined for the element type.
Alternately, a tryShow :: a -> Maybe String
method would also do the trick.
Is there a way to do this? Can I force OverlappingInstances to use the default implementation only when the Show implementation does not apply? Is this guaranteed behaviour?
EDIT: bonus points for anyone who can get the error to also print a stack-trace-like message!