memoization

How does this C++ function use memoization?

#include <vector> std::vector<long int> as; long int a(size_t n){ if(n==1) return 1; if(n==2) return -2; if(as.size()<n+1) as.resize(n+1); if(as[n]<=0) { as[n]=-4*a(n-1)-4*a(n-2); } return mod(as[n], 65535); } The above code sample using memoization to calculate a recursive formula based on some input n. I know t...

Caching delegate results

I have a C# method which accepts a Predicate<Foo> and returns a list of matching items... public static List<Foo> FindAll( Predicate<Foo> filter ) { ... } The filter will often be one of a common set... public static class FooPredicates { public static readonly Predicate<Foo> IsEligible = ( foo => ...) ... } ...but may ...

How do I memoize a recursive function in Lisp?

I'm a Lisp beginner. I'm trying to memoize a recursive function for calculating the number of terms in a Collatz sequence (for problem 14 in Project Euler). My code as of yet is: (defun collatz-steps (n) (if (= 1 n) 0 (if (evenp n) (1+ (collatz-steps (/ n 2))) (1+ (collatz-steps (1+ (* 3 n))))))) (defun ...

Haskell function definition and caching arrays

I have a question about implementing caching (memoization) using arrays in Haskell. The following pattern works: f = (fA !) where fA = listArray... But this does not (the speed of the program suggests that the array is getting recreated each call or something): f n = (fA ! n) where fA = listArray... Defining fA outside of a wh...

Should I use recursion or memoization for an algorithm?

If I have a choice to use recursion or memoization to solve a problem which should I use? In other words if they are both viable solutions in that they give the correct output and can be reasonably expressed in the code I'm using, when would I use one over the other? ...

Static variables in an anonymous function

Hi, I'm trying to mimic static variables on a JavaScript function, with the following purpose: $.fn.collapsible = function() { triggers = $(this).children('.collapse-trigger'); jQuery.each(triggers, function() { $(this).click(function() { collapse = $(this).parent().find('.collapse'); }) }) } How do I save the "co...

Dynamic Programming Recursion and a sprinkle of Memoization

I have this massive array of ints from 0-4 in this triangle. I am trying to learn dynamic programming with Ruby and would like some assistance in calculating the number of paths in the triangle that meet three criterion: You must start at one of the zero points in the row with 70 elements. Your path can be directly above you one row (...

When to use memoization in Ruby on Rails

In mid July 2008 Memoization was added to Rails core. A demonstration of the usage is here. I have not been able to find any good examples on when methods should be memoized, and the performance implications of each. This blog post, for example, suggests that oftentimes, memoization should not be used at all. For something that could p...

Is there a way to caching mechanism for Class::DBI?

I have a set of rather complex ORM modules that inherit from Class::DBI. Since the data changes quite infrequently, I am considering using a Caching/Memoization layer on top of this to speed things up. I found a module: Class::DBI::Cacheable but no rating or any reviews on RT. I would appreciate hearing from people who have used this or ...

Is there a good cached memoization plugin for rails?

I have a model along the lines of: class Account < ActiveRecord::Base has_many :payments has_many :purchases def balance payments.sum(:dollar_amount) - purchases.map{|p| p.dollar_amount}.sum end end I want to memoize the balance method and store it in memcached. The problem, of course, is that the cached value needs to...

In Ruby, should I use ||= or if defined? for memoization?

Should I use if defined? return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find Or ||= @current_user_session ||= UserSession.find I noticed the if defined? method being used more and more recently. Is there any advantage to one over the other? Personally, I prefer ||= for readab...

How can I programmatically detect side effects (compile time or run time)?

I've got an idea for caching that I'm beginning to implement: Memoizing functions and storing the return along with a hash of the function signature in Velocity. Using PostSharp, I want to check the cache and return a rehydrated representation of the return value instead of calling the function again. I want to use attributes to control...

What kinds of functions are candidates for memoization?

I've decided on PostSharp (indistinguishable from magic) to read attributes and memoize functions. The hash of the function call will be the key and the cached (in Velocity) result will be returned instead of calling the function again. Easy peasy, mac-and-cheesy. I've already given up on being able to detect side effects in decorated f...

generic non-invasive cache wrapper

I'm trying create a class which adds functionality to a generic class, without directly interfacing with the wrapped class. A good example of this would be a smart pointer. Specifically, I'd like to create a wrapper which caches all the i/o for one (or any?) method invoked through the wrapper. Ideally, the cache wrapper have the follo...

Thread-safe memoization

Let's take Wes Dyer's approach to function memoization as the starting point: 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; ...

How to get optimization from a "pure function" in C#?

If I have the following function, it is considered pure in that it has no side effects and will always produce the same result given the same input x. public static int AddOne(int x) { return x + 1; } As I understand it, if the runtime understood the functional purity it could optimize execution so that return values wouldn't have to ...

How do I memoize expensive calculations on Django model objects?

I have several TextField columns on my UserProfile object which contain JSON objects. I've also defined a setter/getter property for each column which encapsulates the logic for serializing and deserializing the JSON into python datastructures. The nature of this data ensures that it will be accessed many times by view and template logi...

Ruby Maths Function Memoization

Hi All, I wrote some code that looks like this: def get(x, y) @cachedResults.set(x,y, Math.hypot(x, y)) if @cachedResults.get(x,y).nil? @cachedResults.get(x,y) end Where @cachedResults contained a 2D Array class i wrote (in a few minutes) and the purpose of this function is to make sure that I never have to call Math.hypot twic...

Is it possible to retrieve existing moose objects, rather than create a new one, when the same required attributes are provided?

Suppose i have the following Moose package: package GSM::Cell; use Moose; has 'ID' => (is => 'ro', required => 1); has [qw(BCCH NEIGHBOUR)] => (is => 'rw', default => undef); no Moose; __PACKAGE__->meta->make_immutable; 1; I then create two objects and add the one as the 'NEIGHBOUR' attribute of the other: my $a = GSM::Cell->new(I...

why memoization is not a language feature?

I was wondering... why memoization is not provided natively as a language feature by any language I know about? Edit: to clarify, what I mean is that the language provides a keyword to specify a given function as memoizable, not that every function is automatically memoized "by default", unless specified otherwise. For example, fortran ...