I have a Haskell program which uses Data.Map.!
at several places. After executing the program, there is error message saying element not in the map
.
I am wondering how can I know at which line of the program that uses the Data.Map.!
that emits the error message and what ele开发者_如何学Goment is not found in the map?
The (!)
operator is not intended for looking up things that might not be in the map. While you can catch the resulting error in the IO
monad, it would be very bad style.
Instead, use lookup
, which returns Maybe a
, and in particular, returns Nothing
when the element isn't in the map.
Edit: Okay, I misread your question. Leaving the original answer in case it's useful, but supposing that (!)
really was what you wanted and you're debugging, there are a couple things you could do:
You can temporarily hide
(!)
in the imports, and instead define your own version that useslookup
and throws a more useful error (perhaps containing the key that you tried to look up, if it has a Show instance).You can run the code in the GHCi debugger, and use -fbreak-on-exception to stop the code where the lookup occurs.
You can use the
Debug.Trace
module to add trace statements to your code.
精彩评论