Skip to content

Instantly share code, notes, and snippets.

@megasuperlexa
Last active March 23, 2018 09:12
Show Gist options
  • Save megasuperlexa/2c054815de2f5925013a310bfb010c67 to your computer and use it in GitHub Desktop.
Save megasuperlexa/2c054815de2f5925013a310bfb010c67 to your computer and use it in GitHub Desktop.
Memoize example
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