Declaring a variable without assigning

前端 未结 5 1891
栀梦
栀梦 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: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(IDictionary 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")
    

提交回复
热议问题