Declaring a variable without assignment

Any way to declare a new variable in F # without assigning it a value?

+7
source share
5 answers

See Aidan comment.

If you insist, you can do this:

let mutable x = Unchecked.defaultof<int> 

This will assign an absolute value of zero ( 0 for numeric types, null for reference types, struct-zero for value types).

+16
source

You can also use an explicit field :

 type T = val mutable x : int 
+7
source

It would be interesting to know why the author needs this in F # (a simple example of the intended use would be sufficient).

But I assume that one of the common cases when you can use an uninitialized variable in C # is when you call a function with the out parameter:

 TResult Foo<TKey, TResult>(IDictionary<TKey, TResult> dictionary, TKey key) { TResult value; if (dictionary.TryGetValue(key, out value)) { return value; } else { throw new ApplicationException("Not found"); } } 

Fortunately, in F # you can handle this situation using much better syntax:

 let foo (dict : IDictionary<_,_>) key = match dict.TryGetValue(key) with | (true, value) -> value | (false, _) -> raise <| ApplicationException("Not Found") 
+7
source

I agree with everyone who said "don't do this." However, if you are sure that you are in the case when it is really necessary, you can do this:

 let mutable naughty : int option = None 

... then later to assign a value.

 naughty <- Some(1) 

But keep in mind that everyone who says “change your approach” is probably right. I am in F # code full time, and I never had to declare unassigned "variables".

Another point: although you say that it is not your choice to use F #, I predict that you will soon find that you are lucky to use it!

+4
source

F # variables are immutable by default, so you cannot assign a value later. Therefore, declaring them without an initial value makes them completely useless, and therefore there is no mechanism for this.

It is possible that declaring a mutable variable can be declared without an initial value and is still useful (it can get initial default values, such as C # variables), but the F # syntax does not support this. I would suggest that this is for consistency, and because variable variable slots are not idiomatic F #, so there is little incentive to make special cases to support them.

+2
source

All Articles