How do I write a generic memoize function?

后端 未结 15 1759
情话喂你
情话喂你 2020-12-09 05:25

I\'m writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   retu         


        
15条回答
  •  渐次进展
    2020-12-09 06:17

    Here is a generic C# 3.0 implementation, if it could help :

    public static class Memoization
    {
        public static Func Memoize(this Func function)
        {
            var cache = new Dictionary();
            var nullCache = default(TResult);
            var isNullCacheSet = false;
            return  parameter =>
                    {
                        TResult value;
    
                        if (parameter == null && isNullCacheSet)
                        {
                            return nullCache;
                        }
    
                        if (parameter == null)
                        {
                            nullCache = function(parameter);
                            isNullCacheSet = true;
                            return nullCache;
                        }
    
                        if (cache.TryGetValue(parameter, out value))
                        {
                            return value;
                        }
    
                        value = function(parameter);
                        cache.Add(parameter, value);
                        return value;
                    };
        }
    }
    

    (Quoted from a french blog article)

提交回复
热议问题