3

I'm beginner of haskell.

Now I'm struggling to resolve negative index exception.

But unlike other common language, it seems to me that haskell doesn't show line number where exception occured.

Is it possible to know the line number where exception occured?

Jimmy Choi
  • 45
  • 3
  • It is actually quite uncommon to work with indexes in the first place. Exacly what are you trying to do? – Willem Van Onsem May 12 '21 at 18:10
  • there are a couple of ways how you can get the lines for your own functions (see here: https://stackoverflow.com/questions/35261366/how-to-print-with-line-number-and-stack-trace-in-haskell) – Random Dev May 12 '21 at 18:21
  • 2
    I propose that we mark Carsten's link as a duplicate of this one. It's an excellent question, and pre-existing, but its answers are pretty out of date. (I could do it myself, but I am unusually uncertain of myself in this particular instance, specifically because of the temporal inversion.) Any other votes? – Daniel Wagner May 12 '21 at 20:19
  • (As there were two votes in favor and none against after a day, I have marked the linked question as a dupe.) – Daniel Wagner May 13 '21 at 15:31

1 Answers1

6

These days there are basically two good ways.

  1. Liberally sprinkle HasCallStack constraints through your code, as in

     foo :: HasCallStack => Int -> [a] -> a
     foo n xs = xs !! n
    
  2. Compile with -prof and pass the -xc RTS flag, as in

     ghc -prof foo.hs && ./foo +RTS -xc
    

The latter is easier, the former gives you more control over exactly what things are considered "interesting enough" to put in a stack trace.

Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380