如何在haskell中使表(Data.Map)严格?

发布于 2024-11-07 08:56:35 字数 341 浏览 9 评论 0原文

为了学习 Haskell(很好的语言),我正在尝试 Spoj 中的问题。

我有一个包含 19000 个元素的表,这些元素在编译时都是已知的。 如何使表格严格限制“seq”? 这是我的代码中的一个(强大的)简化示例。

import qualified Data.Map as M

-- table = M.fromList . zip "a..z" $ [1..]  --Upps, incorrect. sorry
table = M.fromList . zip ['a'..'z'] $ [1..]

For learning Haskell (nice language) I'm triying problems from Spoj.

I have a table with 19000 elements all known at compile-time.
How can I make the table strict with 'seq'?
Here a (strong) simplified example from my code.

import qualified Data.Map as M

-- table = M.fromList . zip "a..z" $ [1..]  --Upps, incorrect. sorry
table = M.fromList . zip ['a'..'z'] $ [1..]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随梦而飞# 2024-11-14 08:56:35

我认为您正在 Control.DeepSeq 中寻找 deepseq ,它用于强制对数据结构进行全面评估。

它的类型签名是deepseq :: NFData a =>一个-> b-> b,它的工作原理是在返回第二个参数之前完全评估第一个参数。

table = t `deepseq` t
  where t = M.fromList . zip ['a'..'z'] $ [1..]

请注意,这里仍然存在一些惰性。 table 在您尝试使用它之前不会被评估,但此时整个地图都会被评估。

请注意,正如 luqui 指出的那样,Data.Map 的键已经很严格,因此只有当您希望它的值也很严格时,这样做才有意义。

I think you're looking for deepseq in Control.DeepSeq which is used for forcing full evaluation of data structures.

Its type signature is deepseq :: NFData a => a -> b -> b, and it works by fully evaluating its first argument before returning the second.

table = t `deepseq` t
  where t = M.fromList . zip ['a'..'z'] $ [1..]

Note that there is still some laziness left here. table won't get evaluated until you try to use it, but at that point the entire map will be evaluated.

Note that, as luqui pointed out, Data.Map is already strict in its keys, so doing this only makes sense if you want it to be strict in its values as well.

请恋爱 2024-11-14 08:56:35

一般的答案是,您编写一些必须强制评估整个数据结构的代码。例如,如果您有一个列表:

 strictList xs = if all p xs then xs else []
      where p x = x `seq` True

我确信已经有一些类型类可以递归地应用此类强制以及标准数据类型的实例。

The general answer is, you write some code that must force evaluation of the whole datastructure. For example, if you have a list:

 strictList xs = if all p xs then xs else []
      where p x = x `seq` True

I am sure there is already some type class that would apply such forcing recursively and instances for standard data types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文