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?
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.
You cannot define a free function inside another in C++.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With