Two argument Memoization

后端 未结 5 2084
既然无缘
既然无缘 2021-01-06 07:48

In C# how do I memoize a function with two arguments?

Do I have to curry before memoization?

Wes Dyer wrote the Memoization code I typically use, but now I n

5条回答
  •  走了就别回头了
    2021-01-06 08:38

    You just make an overloaded version of the Memoize method that has three generic types and takes a function with two parameters, and the two arguments. It still returns a parameterless function:

    public static Func Memoize(this Func f, A1 a1, A2 a2)
    {
      R value = default(R);
      bool hasValue = false;
      return () =>
        {
          if (!hasValue)
          {
            hasValue = true;
            value = f(a1,a2);
          }
          return value;
        };
    }
    

    Edit:
    Alternatively, you need to make a custom IEqualityComparer for a KeyValuePair that contains the two arguments, for the Memoize method to be able to return a function with two parameters:

    public static Func Memoize(this Func f, IEqualityComparer> comparer)
    {
       var map = new Dictionary,R>(comparer);
       return (a1,a2) =>
          {
             R value;
             KeyValuePair key = new KeyValuePair(a1,a2);
             if (map.TryGetValue(key, out value)) {
                return value;
             }
             value = f(a1,a2);
             map.Add(key, value);
             return value;
          };
    }
    

提交回复
热议问题