开发者

How to know which element not in Map when using Data.Map.!

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:

  1. You can temporarily hide (!) in the imports, and instead define your own version that uses lookup and throws a more useful error (perhaps containing the key that you tried to look up, if it has a Show instance).

  2. You can run the code in the GHCi debugger, and use -fbreak-on-exception to stop the code where the lookup occurs.

  3. You can use the Debug.Trace module to add trace statements to your code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜