Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable without assigning

Tags:

f#

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

like image 743
cookya Avatar asked Jun 18 '12 15:06

cookya


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

like image 62
Ramon Snir Avatar answered Oct 29 '22 00:10

Ramon Snir


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")
like image 35
Ed'ka Avatar answered Oct 28 '22 22:10

Ed'ka