Last active
August 29, 2019 18:19
-
-
Save panicoenlaxbox/377f15d1d695d906eea625f41dd1578f to your computer and use it in GitHub Desktop.
Memoize in C# inspired by http://inlehmansterms.net/2015/03/01/javascript-memoization/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Newtonsoft.Json; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Func<int, int> factorial = null; | |
factorial = Memoize<int, int>(n => | |
{ | |
Console.WriteLine($"Working for factorial {n}"); | |
if (n == 1) | |
{ | |
return 1; | |
} | |
return n * factorial(n - 1); | |
}); | |
ExecuteFactorialExample(factorial); | |
var sum = Memoize<int[], int>(array => | |
{ | |
Console.WriteLine($"Working for sum {string.Join(",", array)}"); | |
return array.Sum(); | |
}); | |
ExecuteSumExample(sum); | |
} | |
private static void ExecuteSumExample(Func<int[], int> sum) | |
{ | |
Console.WriteLine(sum(new[] { 3 })); | |
Console.WriteLine(sum(new[] { 4, 5 })); | |
Console.WriteLine(sum(new[] { 3 })); | |
Console.WriteLine(sum(new[] { 4, 5 })); | |
Console.WriteLine(sum(new[] { 5, 6, 7 })); | |
//Memoize | |
//[3] not found in cache | |
//Working for sum 3 | |
//3 | |
//[4,5] not found in cache | |
//Working for sum 4,5 | |
//9 | |
//[3] found in cache | |
//3 | |
//[4,5] found in cache | |
//9 | |
//[5,6,7] not found in cache | |
//Working for sum 5,6,7 | |
//18 | |
} | |
private static void ExecuteFactorialExample(Func<int, int> factorial) | |
{ | |
Console.WriteLine(factorial(3)); | |
Console.WriteLine(factorial(3)); | |
Console.WriteLine(factorial(4)); | |
Console.WriteLine(factorial(3)); | |
//Memoize | |
//3 not found in cache | |
//Working for factorial 3 | |
//2 not found in cache | |
//Working for factorial 2 | |
//1 not found in cache | |
//Working for factorial 1 | |
//6 | |
//3 found in cache | |
//6 | |
//4 not found in cache | |
//Working for factorial 4 | |
//3 found in cache | |
//24 | |
//3 found in cache | |
//6 | |
} | |
public static Func<T, TResult> Memoize<T, TResult>(Func<T, TResult> fn) | |
{ | |
Console.WriteLine(nameof(Memoize)); | |
var cache = new Dictionary<string, TResult>(); | |
return n => | |
{ | |
var key = JsonConvert.SerializeObject(n); | |
if (cache.ContainsKey(key)) | |
{ | |
Console.WriteLine($"{key} found in cache"); | |
return cache[key]; | |
} | |
Console.WriteLine($"{key} not found in cache"); | |
var value = fn(n); | |
cache[key] = value; | |
return value; | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment