9

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

5
  • 7
    Why 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#.
    – Aidan
    Jun 18, 2012 at 15:51
  • 2
    It wasn't my choice to use this language :) It's just an option i currently need - is it possible?
    – cookya
    Jun 18, 2012 at 15:55
  • 10
    It 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! Jun 18, 2012 at 16:15
  • 2
    As 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. Jun 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? May 14, 2022 at 15:51

5 Answers 5

16

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

1
  • or Unchecked.defaultof<_>
    – eoleary
    Jan 31, 2016 at 20:20
8

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")
2
  • 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
7

You can also use explicit field syntax:

type T =
  val mutable x : int
4

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!

2

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.

7
  • 4
    This is confusing and misleading. F# does support default-initialized variables like C# and there is a mechanism for later re-assignment.
    – Daniel
    Jun 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.
    – kvb
    Jun 19, 2012 at 14:25
  • @kvb: Isn't Ramon's answer an example of a default-initialized variable?
    – Daniel
    Jun 19, 2012 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.