Simple debugging in Haskell

前端 未结 5 2119
醉话见心
醉话见心 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 19:45

    Other answers link the official doco and the Haskell wiki but if you've made it to this answer let's assume you bounced off those for whatever reason. The wikibook also has an example using Fibonacci which I found more accessible. This is a deliberately basic example which might hopefully help.

    Let's say we start with this very simple function, which for important business reasons, adds "bob" to a string, then reverses it.

    bobreverse x = reverse ("bob" ++ x)
    

    Output in GHCI:

    > bobreverse "jill"
    "llijbob"
    

    We don't see how this could possibly be going wrong, but something near it is, so we add debug.

    import Debug.Trace
    
    bobreverse x = trace ("DEBUG: bobreverse" ++ show x) (reverse ("bob" ++ x))
    

    Output:

    > bobreverse "jill"
    "DEBUG: bobreverse "jill"
    llijbob"
    

    We are using show just to ensure x is converted to a string correctly before output. We also added some parenthesis to make sure the arguments were grouped correctly.

    In summary, the trace function is a decorator which prints the first argument and returns the second. It looks like a pure function, so you don't need to bring IO or other signatures into the functions to use it. It does this by cheating, which is explained further in the linked documentation above, if you are curious.

提交回复
热议问题