Declaring a variable without assigning

前端 未结 5 1892
栀梦
栀梦 2020-12-19 06:23

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

相关标签:
5条回答
  • 2020-12-19 06:40

    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.

    0 讨论(0)
  • 2020-12-19 06:53

    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!

    0 讨论(0)
  • 2020-12-19 06:56

    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")
    
    0 讨论(0)
  • 2020-12-19 06:58

    You can also use explicit field syntax:

    type T =
      val mutable x : int
    
    0 讨论(0)
  • 2020-12-19 07:02

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

    0 讨论(0)
提交回复
热议问题