Home > Great Links > Memoization using C#

Memoization using C#

Found a good example of Memoization using C#, Blogmarking for future reference
via http://www.infoq.com/news/2007/01/CSharp-memory via http://ayende.com/Blog/archive/2008/04/13/Challenge-calling-generics-without-the-generic-type.aspx (re: Challenge: calling generics without the generic type

4/13/2008 9:07 PM
Bryan Watts)

public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
  var map = new Dictionary<A, R>();
  return a =>
    {
      R value;
      if (map.TryGetValue(a, out value))
        return value;
      value = f(a);
      map.Add(a, value);
      return value;
    };
}

Func<int, int> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
fib = fib.Memoize();
Advertisements
Categories: Great Links
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: