- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在尝试运行诸如此类的中等输入时内存不足:
variation_models 15 25
同时为 ncars 运行更高的数字似乎在速度和内存使用方面产生了巨大差异。
预计会放缓(有更多的东西要比较),但内存使用量的指数增长对我来说没有意义
import Control.Monad
orderedq f [] = True
orderedq f (x:[]) = True
orderedq f (x:y:zs) = f x y && orderedq f (y:zs)
num_orderedq = orderedq (<=)
adds_up_to n xs = n == sum xs
both_conditions f g xs = f xs && g xs
variation_models ncars nlocations =
filter (both_conditions (adds_up_to nlocations) num_orderedq) $ replicateM ncars [1..nlocations-ncars+1]
是什么导致了内存使用量的巨大差异? replicateM
?
最佳答案
我认为您在其他地方已经看到您的特定问题(创建总和为给定数字的有序整数列表)使用替代算法更好地解决,而不是过滤大量整数列表。
但是,回到您原来的问题,可以构造一个等价于:
replicateM p [1..n]
它以指数时间(当然)但恒定空间运行。
问题是这个表达式或多或少等同于递归:
badPower 0 _ = pure []
badPower p n = [x:xs | x <- [1..n], xs <- badPower (p-1) n]
因此,在列表理解中,对于每个选定的 x
, 整个列表 badPower (p-1) n
需要从头重新生成。 GHC 明智地决定保留 badPower (p-1) n
这样就不需要每次都重新计算。所以,badPower p n
调用需要整个 badPower (p-1) n
列表保存在内存中,已经占了 n^(p-1)
元素和指数内存使用,即使不考虑badPower (p-2) n
等
如果你只是翻转隐式循环的顺序:
goodPower 0 _ = pure []
goodPower p n = [x:xs | xs <- goodPower (p-1) n, x <- [1..n]]
这解决了问题。即使列表goodPower (p-1) n
是“大”,我们取它的第一个元素,使用它n
x
的每个值的次数然后可以丢弃它并移动到下一个元素。所以,goodPower (p-1) n
可以在使用时进行垃圾回收。
请注意 goodPower
以不同于 badPower
的顺序生成元素,列表的第一个坐标变化最快,而不是最后一个。 (如果这很重要,您可以 map reverse $ goodPower ...
。虽然 reverse
很“慢”,但它仅适用于此处的短列表。)
无论如何,以下程序(实际上)永远运行,但在恒定空间中运行:
power :: Int -> [a] -> [[a]]
power 0 _ = [[]]
power p lst = [x:xs | xs <- power (p-1) lst, x <- lst ]
main = do
print $ length (power 15 [1..11])
关于haskell 用有限列表耗尽内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61875763/
我有一个关于复杂性的简单问题。我在 Java 中有这段代码: pairs是 HashMap包含 Integer作为键,它的频率为 Collection作为一个值。所以: pairs = new Has
对于我的应用程序,我需要在 Coq 中使用和推理有限映射。谷歌搜索我发现 FMapAVL 似乎非常适合我的需求。问题是文档很少,我还没有弄清楚我应该如何使用它。 作为一个简单的例子,考虑以下使用对列表
我有一个主表tblAssetMaster A和一个移动表tblMovement M。 我想提取所有 Assets 及其当前位置,因此需要获取每个 Assets 的最新移动条目。 字段 A: Asset
我想让我的网站内容居中,但仅限于网页的特定宽度。所以当它超过 500px 时,我希望内容被修复,无法进一步拉伸(stretch)。无论如何都要这样做,还是我最好把所有东西都修好?希望有意义的是添加一些
我正在尝试批量删除 Backbone 模型的集合,如下所示...... collection.each(function(model, i){ model.destroy(); }); 我发现当每
我想要一个软件环境,在其中我可以在具有特定资源的硬件上测试我的软件的速度。例如,当我的主机硬件是具有 12GB RAM 的 3GHz 四核 amd64 时,该程序在具有 24 Mb RAM 的 800
在 Eclipse 中,我得到了 BigInteger.valueOf(2).pow(31093) 的值,但没有得到 BigInteger.valueOf(2).pow(31094) 的值(它是空的)
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求提供代码的问题必须表现出对所解决问题的最低限度理解。包括尝试过的解决方案、为什么它们不起作用,以及预
我想将 2 个表从本地 sql server 2000 上传到托管的 mysql。第一个表有 17 列和 680 行,其他 10 列和 8071 行。 我首先使用 xampp mysql 尝试离线,它
我在 S3 中自动生成并保存了静态 html 文件。有时文件大小达到 2mb。是否可以使用javascript来获取html文件的一部分,显示它,当用户到达页面底部时,获取下一部分等等? 最佳答案 X
我是一名优秀的程序员,十分优秀!