Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good way to avoid "sharing"?

Tags:

Suppose that someone would translate this simple Python code to Haskell:

def important_astrological_calculation(digits):
  # Get the first 1000000 digits of Pi!
  lucky_numbers = calculate_first_digits_of_pi(1000000)
  return digits in lucky_numbers

Haskell version:

importantAstrologicalCalculation digits =
  isInfixOf digits luckyNumbers
  where
    luckyNumbers = calculateFirstDigitsOfPi 1000000

After working with the Haskell version, the programmer is astonished to discover that his Haskell version "leaks" memory - after the first time his function is called, luckyNumbers never gets freed. That is troubling as the program includes some more similar functions and the memory consumed by all of them is significant.

Is there an easy and elegant way to make the program "forget" luckyNumbers?

like image 874
yairchu Avatar asked Jul 07 '11 16:07

yairchu


1 Answers

In this case, your pidigits list is a constant (or "constant applicative form ), and GHC will probably float it out, calculate it once, and share amongst uses. If there are no references to the CAF, it will be garbage collected.

Now, in general, if you want something to be recalculated, turn it into a function (e.g. by adding a dummy () parameter). Examples in the linked question on CAFs: How to make a CAF not a CAF in Haskell?

like image 179
Don Stewart Avatar answered Oct 26 '22 23:10

Don Stewart