Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check the type of a local variable?

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.

like image 990
Nick Brunt Avatar asked Feb 09 '12 11:02

Nick Brunt


People also ask

How do you check the type of a variable?

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.

How do I find local variables?

You can view local variables and parameters by entering the dv command or the dt command in the Debugger Command window.

What kind of variables are local variables in a function?

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.

How do you know if a variable is global or local?

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.


2 Answers

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].

like image 82
dying_sphynx Avatar answered Nov 10 '22 21:11

dying_sphynx


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.

like image 21
Rob Agar Avatar answered Nov 10 '22 19:11

Rob Agar