一种避免“共享”的好方法? [英] A good way to avoid "sharing"?

查看:104
本文介绍了一种避免“共享”的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有人会把这个简单的Python代码翻译成Haskell:

def important_astrological_calculation(digits ):
#获取Pi的前1000000个数字!
lucky_numbers = calculate_first_digits_of_pi(1000000)
在lucky_numbers中返回数字

Haskell版本:

  importantAstrologicalCalculation digits = 
isInfixOf digits luckyNumbers
where
luckyNumbers = calculateFirstDigitsOfPi 1000000 $ b $在使用Haskell版本后,程序员惊讶地发现他的Haskell版本泄漏了内存 - 在第一次调用他的函数时, luckyNumbers 永远不会被释放。这很麻烦,因为该程序包含了一些更类似的功能,并且所有这些功能都消耗了大量内存。


是否有一种简单而优雅的方式让程序忘记 luckyNumbers

解决方案

在这种情况下,您的pidigits列表是不变的(或者不变的应用形式
),GHC可能会浮出来,计算一次,并在各种用途之间共享。如果没有CAF的引用,它将被垃圾收集。



现在,一般来说,如果你想重新计算一些东西,把它变成一个函数(例如通过添加一个虚拟的()参数)。关于CAF链接问题的示例:如何在哈斯克尔做一个CAF而不是CAF?


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?

解决方案

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?

这篇关于一种避免“共享”的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆