Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine a type in F#?

Tags:

f#

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#?

like image 228
jubibanna Avatar asked Dec 02 '22 10:12

jubibanna


2 Answers

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.

like image 182
Fyodor Soikin Avatar answered Jan 04 '23 19:01

Fyodor Soikin


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.

like image 38
rmunn Avatar answered Jan 04 '23 19:01

rmunn