Home > OS >  I wonder what is exact meaning of "return"
I wonder what is exact meaning of "return"

Time:02-16

I've studying reflexive method and dictionary class(I'm nor sure it's correct in English cuz I'm Korean) and there was a example calculating fibonacci in C# book.

class Fibonacci
{
    private static Dictionary<int, long> memo = new Dictionary<int, long>();
    
    public static long Get(int i)
    {
        if (i < 0) { return 0; }
        if (i == 1) { return 1; }

        if (memo.ContainsKey(i)) { return memo[i]; }
        else
        {
            long value = Get(i - 2)   Get(i - 1);
            memo[i] = value;
            return value;
        }
    }
}

I wonder which code puts key and value into dictionary list. At i<0 i==0 line I think it seems "return" does that job but at

if (memo.ContainsKey(i)) { return memo[i]; }

here return does its job as passing(handing over?) the code if there is same key in the dictionary list. So I'm curious what does "return" actually mean. Help!

CodePudding user response:

The i < 0 and i == 1 lines do not use the dictionary at all. For those early terms, the dictionary lookup would be slower than the calculation anyway.

The if (memo.ContainsKey(i)) { return memo[i]; } line also does not set anything new in the dictionary. It reads from the dictionary, but does not write to it, because either the value is already there or we don't know what to write yet. Today, I might update this code to use TryGetValue() instead, in order to save one hash calculation and lookup on success.

The line that actually writes to the dictionary is this:

memo[i] = value;

Additionally, the reason the dictionary is named memo is because the code uses a technique called memoization.

CodePudding user response:

memo[i] = value; adds value to the dictionary. To be more precise, it adds the key value pair if the key didn't exist, or overwrites the value for the key if it existed. Take a look:

private static Dictionary<int, long> memo = new Dictionary<int, long>();

public static void AddToDictionary(int key, long value)
{
    memo[key] = value;
    foreach (var item in memo)
    {
        System.Console.WriteLine($"{item.Key}: {item.Value}");
    }
}

Result:

Adding 1,2 key-value pair.
1: 2
Adding 1,8 key-value pair.
1: 8
Adding 2,2 key-value pair.
1: 8
2: 2
  •  Tags:  
  • c#
  • Related