What is the best way to test and interact with inner functions defined inside a toplevel function?

DebuggingHaskellRead Eval-Print-LoopGhci

Debugging Problem Overview


When I program in Javascript, I find it extremely convenient to be able to use the debugger to halt program execution at any point and to be able to runs commands and inspect variables from there.

Now, back in Haskell, is there a way to run arbitrary functions in the interactive GHCI REPL or am I limited to things declared at the toplevel?

What is the "standard" approach to working and debugging inner functions and values?

Debugging Solutions


Solution 1 - Debugging

When you are stopped at a breakpoint in GHCi, you can access anything that's in scope. Let's say you have a function like this:

foo :: Int -> Int
foo x = g (x + 2)
  where g y = x^y 

You can set a breakpoint on foo and try calling it:

> :break foo
Breakpoint 1 activated at /tmp/Foo.hs:(2,1)-(3,17)
> foo 42
Stopped at /tmp/Foo.hs:(2,1)-(3,17)
_result :: Int = _

g is not in scope yet at this point, so we have to step once:

[/tmp/Foo.hs:(2,1)-(3,17)] > :step
Stopped at /tmp/Foo.hs:2:9-17
_result :: Int = _
g :: Integral b => b -> Int = _
x :: Int = 42

Now that g is in scope, we can use it like any top-level function:

[/tmp/Foo.hs:2:9-17] > g 2
1764
[/tmp/Foo.hs:2:9-17] > g 3
74088

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhugomgView Question on Stackoverflow
Solution 1 - DebugginghammarView Answer on Stackoverflow