Simple debugging in Haskell

前端 未结 5 2116
醉话见心
醉话见心 2021-02-07 19:04

I am new to Haskell. Previously I have programmed in Python and Java. When I am debugging some code I have a habit of littering it with print statements in the midd

5条回答
  •  既然无缘
    2021-02-07 20:00

    I really liked Dons short blog about it: https://donsbot.wordpress.com/2007/11/14/no-more-exceptions-debugging-haskell-code-with-ghci/

    In short: use ghci, example with a program with code called HsColour.hs

     $ ghci HsColour.hs
        *Main> :set -fbreak-on-exception
        *Main> :set args "source.hs"
    

    Now run your program with tracing on, and GHCi will stop your program at the call to error:

     *Main> :trace main
        Stopped at (exception thrown)
    

    Ok, good. We had an exception… Let’s just back up a bit and see where we are. Watch now as we travel backwards in time through our program, using the (bizarre, I know) “:back” command:

      [(exception thrown)] *Main> :back
        Logged breakpoint at Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)
        _result :: [String]
    

    This tells us that immediately before hitting error, we were in the file Language/Haskell/HsColour/Classify.hs, at line 19. We’re in pretty good shape now. Let’s see where exactly:

     [-1: Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)] *Main> :list
        18  chunk :: String -> [String]
            vv
        19  chunk []    = head []
        20  chunk ('\r':s) = chunk s -- get rid of DOS newline stuff
        21  chunk ('\n':s) = "\n": chunk s
                                           ^^
    

提交回复
热议问题