Purity (D2 standard libraries / object.d)

Jason House jason.james.house at gmail.com
Fri Jan 9 17:45:57 PST 2009


Walter Bright wrote:

> Memoization and purity don't mix. 

True, but...

All pure functions can be memoized.  They can be memoized by the caller of the pure function, or the pure function could be rewritten to automatically memoize.

When writing a pure but potentially costly function, the coder may consider memoization.  They must predict how frequently the function would get called with the same input.  They must also decide if the time/space trade-off is worth it for the program as a whole and how inconvenient it would be to call the function.  If it's called from another pure function, well... they don't mix.

All-in-all, memoization is a tough call to make.  For library writers, it's even tougher.  They may not know how their code would get used and may be unable to make the call about memoization.  It's possible to provide a pure function and a memoized alternative.  Of course, there are many memoization options available, especially when memory space is restricted or various thread safety/locking methods may be desired.  A library writer may just declare that if the user wants memoization that they should use a memoization library to do it.

Anyone who writes an inheritable classes also have to predict if the writers of classes that inherit from their class will want to memoize or not.  Some may forbid it because then they can declare the function pure.  Others will feel like they can't declare any virtual functions as pure (and therefore allow memoization).

> For each function, you'll have to pick
> which way you want to go. I don't see what that has to do with D's
> future, though, the language allows either.

Somehow, I had the impression that D might use memoization as some kind of optimization once pure functions are embraced.  That was probably a misunderstanding on my part.

I do think that writers of generic/library/inheritable code will continuously revisit the question of memoization.  That may affect the future of D usage, but not the underlying language specification.



More information about the Digitalmars-d mailing list