Any way to declare a new variable in F# without assigning a value to it?
-
7Why would you use F# to do that? Remember that in functional programming there are actually no variables, just functions with values, so your question goes against the grain of F#.– AidanJun 18, 2012 at 15:51
-
2It wasn't my choice to use this language :) It's just an option i currently need - is it possible?– cookyaJun 18, 2012 at 15:55
-
10It is amazing how infrequently you need this feature in F#. Coming from C#, this is one of the early anxieties you experience moving to F#. But the key to learning to work without mutable variables is realizing that in F#, everything is an expression! Now I cringe every time I need to declare an unassigned variable in C#, only to assign it immediately after based on the outcome of some if / then statement!– Stephen SwensenJun 18, 2012 at 16:15
-
2As several people have pointed out, it would be good if you would amend your question to spell out your use case. Might help people to give you better answers.– Onorio CatenacciJun 20, 2012 at 14:56
-
People always write that this is not needed. But consider this: You're inside a calculation expression and want to return early if the value could not be initialized: ` task { let! result = try GetValueAsync() with :? SomeException -> return () } ` This complains that you cannot use the return there. A separate declaration could solve this, right? Do you know a better, idiomatic solution?– Abrißbirne 66May 14, 2022 at 15:51
5 Answers
See Aidan's comment.
If you insist, you can do this:
let mutable x = Unchecked.defaultof<int>
This will assign the absolute zero value (0
for numeric types, null
for reference types, struct-zero for value types).
It would be interesting to know why the author needs this in F# (simple example of intended use would suffice).
But I guess one of the common cases when you may use uninitialised variable in C# is when you call a function with 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");
}
}
Luckily in F# you can handle this situation using much nicer syntax:
let foo (dict : IDictionary<_,_>) key =
match dict.TryGetValue(key) with
| (true, value) -> value
| (false, _) -> raise <| ApplicationException("Not Found")
-
Unfortunately I think this doesn't work if the out parameter is not the last parameter in the function May 22, 2017 at 15:12
-
I had exactly this use case and I had no idea TryGetValue() has an overload that returns a tuple like that! The documentation states that it returns a bool. How did you know? Where is it documented? learn.microsoft.com/en-us/dotnet/api/… Dec 5, 2019 at 18:56
I agree with everyone who has said "don't do it". However, if you are convinced that you are in a case where it really is necessary, you can do this:
let mutable naughty : int option = None
...then later to assign a value.
naughty <- Some(1)
But bear in mind that everyone who has said 'change your approach instead' is probably right. I code in F# full time and I've never had to declare an unassigned 'variable'.
Another point: although you say it wasn't your choice to use F#, I predict you'll soon consider yourself lucky to be using it!
F# variables are by default immutable, so you can't assign a value later. Therefore declaring them without an initial value makes them quite useless, and as such there is no mechanism to do so.
Arguably, a mutable variable declaration could be declared without an initial value and still be useful (it could acquire an initial default like C# variables do), but F#'s syntax does not support this. I would guess this is for consistency and because mutable variable slots are not idiomatic F# so there's little incentive to make special cases to support them.
-
4This is confusing and misleading. F# does support default-initialized variables like C# and there is a mechanism for later re-assignment.– DanielJun 18, 2012 at 18:15
-
2"F# variables are by default immutable"--hence we usually refer to them not as "variables" but "values" Jun 18, 2012 at 20:44
-
I can see why you'd do that. My FP experience comes mostly from the direction of Haskell, where I've always called them variables (and there's no way to make them mutable at all). However I'm aware some of these conventions are a bit different in the F# world. Jun 19, 2012 at 8:31
-
@Daniel - I don't think that's quite right. F# provides a way to declare default-initialized fields, but not uninitialized local variables.– kvbJun 19, 2012 at 14:25
-
@kvb: Isn't Ramon's answer an example of a default-initialized variable?– DanielJun 19, 2012 at 14:31