← Back to context

Comment by yummyfajitas

14 years ago

If you wish to debug a function in Haskell you can't insert a printf to inspect its inner workings unless that function happens to be on the IO monad.

Sure you can.

    f x =
        let intermediate = 2*x
            intermediate2 = unsafePerformIO $ do
                              putStrLn ("intermediate value is " ++ (show intermediate))
                              return intermediate
        in
          (intermediate2 * intermediate2)

Output:

    intermediate value is 6
    Result is 36

It's a little uglier, since you need to make sure intermediate2 is actually evaluated. The better way to go would be:

    f x = 
        let intermediate = intermediateComputation x
        in 
          (intermediate*intermediate)

    intermediateComputation x = 2*x

And then you just don't expose intermediateComputation to stuff outside the module. This has the advantage that you can use quickCheck on intermediateComputation. If the value isn't what you think it is, quickCheck will tell you what it actually is.