Simple question. Is it possible to check the type of a variable that is only alive within a function?
For example:
main = do
x <- something
How can I check the type of x
?
I can't do :type x
in ghci because x
is not global.
To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.
You can view local variables and parameters by entering the dv command or the dt command in the Debugger Command window.
Local Variables A local variable is a variable which is either a variable declared within the function or is an argument passed to a function. As you may have encountered in your programming, if we declare variables in a function then we can only use them within that function.
Global variables are declared outside any function, and they can be accessed (used) on any function in the program. Local variables are declared inside a function, and can be used only inside that function. It is possible to have local variables with the same name in different functions.
Another way (quite similar to RobAgar's and hacky as well) is to explicitly specify some wrong type for the local variable in question, e.g.:
main = do
x <- getArgs
x :: () -- let's cast it to unit! ;)
print $ head x
Then ghci will give us an error:
Couldn't match expected type `()' with actual type `[String]'
which shows that the actual type of "x" is [String].
There is a hacky way:
main = do
x <- something
foo x
where foo
is any old function which doesn't take an argument of the type you think x
might be. You'll get a nice error from GHC which includes the type expected by foo
and the type actually passed in.
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