What is the most efficient way to memoize in Haskell?

What is the fastest way to memoize a recursive function in Haskell?

Reference Information. I recently resolved Project Euler issues at Haskell. Many require many calculations of a recursively defined combinatorial or number-theoretic function, such as Fibonacci numbers. Performance is greatly improved if such functions are remembered, 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 a state monad. The tree-based solution proposed in this answer , and such solutions seem pretty common. To give another example, see this blog post . I saw other solutions using the built-in functions. There is one in section 2 here with fix, and, in addition, it seems that the compiler can sometimes massage in memoizing without additional work. There are also several ready-made solutions .

I am wondering which memoization method is the fastest in practice for the functions used in Project Euler. My intuition says that the hashtables library is because hash tables seem to be the preferred dictionary structure in imperative languages. Purely functional tree solutions are cool, but my Googling tells me that they are strictly worse than hash tables in terms of asymptotic performance.

Edit

A few comments said that this question is too broad to answer, and upon reflection I agree. So let me give you two concrete examples of functions for memoize: a function that recursively computes the nth Fibonacci number, and a method that recursively computes Catalan numbers. I would like to repeatedly calculate these functions for large n.

, , , - memoization.

+4
1

n- , , memoize, . (f n-1, f n) . , .

:

fibs :: [Integer]
fibs = fibcreator 0 1
  where
    fibcreator a b = a : fibcreator b (a+b)

nth = take n fibs

, , :

  • m = [e11 = 1, e12 = 1, e21 = 1, e22 = 0]
  • n- , m '= m ^ (n-1)
  • e11 m ' n-

, , 17 ,

m' = ((((m^2)^2)^2)^2) * m

. , Haskell , . :

data Matrix = Matrix Integer Integer Integer Integer

instance Num Matrix where
  (*) (Matrix a11 a12 a21 a22) (Matrix b11 b12 b21 b22)
   = Matrix (a11*b11 + a12*b21) (a11*b12 + a12*b22) (a21*b11 + a22*b21) (a21*b12 + a22*b22)

fib4 :: Integer -> Integer
fib4 0 = 0
fib4 n = x
  where
    (Matrix x _ _ _) = Matrix 1 1 1 0 ^ (n-1)
+1

Source: https://habr.com/ru/post/1667962/


All Articles