两个参数记忆化 [英] Two argument Memoization

查看:152
本文介绍了两个参数记忆化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中我如何memoize的函数有两个参数?

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

我必须记忆化之前,咖喱?

Do I have to curry before memoization?

韦斯代尔写了记忆化code 我通常使用,但现在我需要两个参数

Wes Dyer wrote the Memoization code I typically use, but now I need two arguments

推荐答案

您只需要把memoize的方法有三个泛型类型,并采取有两个参数,这两个参数的函数的重载版本。它仍然会返回一个无参数功能:

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<R> Memoize<A1,A2,R>(this Func<A1,A2,R> f, A1 a1, A2 a2)
{
  R value = default(R);
  bool hasValue = false;
  return () =>
    {
      if (!hasValue)
      {
        hasValue = true;
        value = f(a1,a2);
      }
      return value;
    };
}

编辑:
另外,你需要创建一个自定义的IEqualityComparer为包含两个参数的KeyValuePair,为memoize的方法能够返回一个函数有两个参数:


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<A1,A2,R> Memoize<A1,A2,R>(this Func<A1,A2,R> f, IEqualityComparer<KeyValuePair<A1,A2>> comparer)
{
   var map = new Dictionary<KeyValuePair<A1,A2>,R>(comparer);
   return (a1,a2) =>
      {
         R value;
         KeyValuePair<A1,A2> key = new KeyValuePair<A1,A2>(a1,a2);
         if (map.TryGetValue(key, out value)) {
            return value;
         }
         value = f(a1,a2);
         map.Add(key, value);
         return value;
      };
}

这篇关于两个参数记忆化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆