What's the fastest way to memoize a recursive function in Haskell?
Background: Recently I have been solving Project Euler problems in Haskell. Many require many computations of a recursively defined combinatorial or number-theoretical function, for example the Fibonacci numbers. Performance improves dramatically if such functions are memoized, that is, the results of the function are cached for later use.
I have seen many solutions to this problem. The most elegant seems to be this. One uses Data.IntMap (or hash tables) and the State monad. A tree based solution suggested in this answer, and such solutions seem fairly common. To give another example, see this blog post. I've seen other solutions using built-in functions. There's one in section 2 here with the fix
, and further it seems that the compiler can sometimes be massaged into memoizing without additional work. There's also several prebuilt solutions.
I'm wondering which memoization method is fastest in practice for the kinds of functions used in Project Euler. My intuition says the hashtables library is, since hash tables seem to be the preferred dictionary structure in imperative languages. The purely functional tree solutions are cool, but my Googling tells me they're strictly worse than hash tables in terms of asymptotic performance.
Edit
A few comments said this question is too broad to answer, and upon reflection I agree. So let me give two concrete examples of functions to memoize: a function that computes the n'th Fibonacci number recursively, and one that computes the Catalan numbers recursively. I would like to compute these functions many times for large n.
I'm aware there are explicit formulas for these, but let's ignore that, because the real point here is to use them to benchmark memoization techniques.
IntMap
are slower than hash maps in terms of asymptotic performance, yes. Asymptotics aren't everything, though.IntMap
has a number of other desirable properties, such as avoiding the overhead of hashing, behaving well when used in a persistent manner, etc. For normal usagesIntMap
's performance is competitive with a hash table. – Benjamin Hodgson