Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a function is being memoized in Haskell?

I've got a Haskell program that is performing non linearly performance wise (worse then O(n)).

I'm trying to investigate whether memoization is taking place on a function, can I verify this? I'm familiar with GHC profiling - but I'm not too sure which values I should be looking at?

A work around is too just plug some values and observe the execution time - but it's not ideal.

like image 668
Chris Stryczynski Avatar asked Jan 02 '19 10:01

Chris Stryczynski


People also ask

Does Haskell automatically Memoize?

Most Haskell compilers and interpreters (all of them that I know of actually) do not memoize polymorphic structures, so m2's internal list is recreated every time it's called, where m1's is not.

Does Haskell Memoize functions?

The trick is to turn a function into a value because, in Haskell, functions are not memoized but values are.


1 Answers

As far as I know there is no automatic memoization in Haskell.

That said there seems to be an optimization in GHC that caches values for parameterless function like the following

rightTriangles = [ (a,b,c) | 
    c <- [1..], 
    b <- [1..c], 
    a <- [1..b], 
    a^2 + b^2 == c^2]

If you try out the following in GHCi twice, you'll see that the second call ist much faster:

ghci > take 500 rightTriangles
like image 167
Thomas Mahler Avatar answered Oct 18 '22 02:10

Thomas Mahler