In Python, I could see the variable's type by typing:
>>> i = 123
>>> type(i)
<type 'int'>
Is there a way to do this in F#?
F# is a .NET language, and in .NET all types are descendants of System.Object
, which has a GetType
method:
let i = 123
let t = i.GetType()
Having said that, I must strongly urge you not to rely on runtime type information, except for debugging or similar purposes. Doing so will make your program way less maintainable and will come back to bite you in the long run.
In Python you can get away with this, because Python is dynamically typed anyway, so one more check deferred to runtime doesn't really make a difference. But F# is statically typed, and by deferring types to runtime you throw away any support the compiler can provide.
If you're wanting to do this in F# Interactive, you just need to evaluate the variable by typing its name (followed by ;;
as with any other expression at the F# Interactive prompt). I.e., if you've already executed let num = 123
, then you just type num;;
at the F# Interactive prompt and you'll see the following printed out:
val it : int = 123
The word val
means that F# Interactive is describing a value. The name it
is a special name in F# Interactive, assigned to the last value that was evaluated. Then comes a colon, the value's type (in this case, int
), then an equals sign, and then the value is printed out.
So all you have to do to see the value and type of a variable in F# Interactive is to just type that variable followed by ;;
. Simple.
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