Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 576
hugomg Avatar asked Apr 03 '12 05:04

hugomg


People also ask

How do you define a function inside another function in Python?

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.

Should you define a function inside a function?

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.

Can a function be defined inside another function in C++?

You cannot define a free function inside another in C++.


1 Answers

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 
like image 99
hammar Avatar answered Sep 21 '22 14:09

hammar