-
-
Save megasuperlexa/2c054815de2f5925013a310bfb010c67 to your computer and use it in GitHub Desktop.
Memoize example
This file contains hidden or 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.Concurrent; | |
using System.Diagnostics; | |
public static class Program | |
{ | |
public static Func<T, V> MemoizeExt<T, V>(this Func<T, V> f) => a => | |
new ConcurrentDictionary<T, V>().GetOrAdd(a, f); | |
public static Func<T, V> Memoize<T, V>(Func<T, V> f) => a => | |
new ConcurrentDictionary<T, V>().GetOrAdd(a, f); | |
public static int DoIt(string a) => a.Length; | |
static void Main() | |
{ | |
Console.WriteLine(DoIt("aaaabba")); | |
Console.WriteLine(DoIt("bbb")); | |
// extension method: does not compile | |
//var cachedDoit = DoIt.MemoizeExt(); | |
// static method: does not compile either | |
// isn't DoIt() signature compatible with Func<string, int> ? | |
//var cachedDoit = Memoize(DoIt); | |
// static with explicit generic types: it works! | |
// DoIt() signature IS compatible with Func<string, int>, but we have to specify types | |
// but it is ugly, what if there's 3, 4 or more parameters | |
var cachedDoit = Memoize<string, int>(DoIt); | |
Console.WriteLine(cachedDoit("aaaabba")); | |
Console.WriteLine(cachedDoit("bbb")); | |
Console.Read(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment