Haskell:使用严格性指南 [英] Haskell: Guidelines for using Strictness

查看:140
本文介绍了Haskell:使用严格性指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,我正在寻找 tagsoup 库。他们有一个像这样定义的数据结构:

$ p $ data标签str
= TagOpen str [属性str]
| TagClose str
| TagText str
| TagComment str
| TagWarning str
| TagPosition!Row!Column

type Row = Int
type Column = Int

那么究竟是什么因素决定 TagPosition 应该是严格的?是否有任何推荐的指导原则? 对于简单的非结构化数据类型,如 Int Double ,将它们转换为严格的字段通常是一个很好的默认值。这使得他们的空间消耗非常可预测(并且不变)。尽管执行不必要的计算可能会降低性能,但这通常不太可能。例如,跟踪某个职位通常非常简单且便宜,因此在业绩方面没有什么可害怕的,并且具有可预测的空间行为更为重要。

对简单类型进行严格处理的另外一个好处是,它们通常可以被解压缩,即直接存储在构造函数中,而不是通过额外的间接寻址(有编译器或编译器标志)。对于小型类型,这通常是一个优势。

对于结构化数据类型,如列表或树,情况要复杂得多。一个简单的在这里很少有帮助,因为它只强制WHNF。就空间而言,评估列表或树也可能比未评估的thunk更容易成本更高。尽管如此,有时候这样做也是很有意义的。在这种情况下,您通常会使用函数(所谓的智能构造函数)来封装构造函数,该函数通过在适当的位置调用 deepseq 来建立严格不变式。


Is there any recommend guidelines when to use strictness in Haskell ?

For example, I was looking on the tagsoup library. They have one of their data structure defined like this:

data Tag str    
    = TagOpen str [Attribute str]
    | TagClose str
    | TagText str
    | TagComment str
    | TagWarning str
    | TagPosition !Row !Column 

type Row = Int 
type Column = Int

So on what factor exactly do they decide that TagPosition should be strict ? Are there any recommend guidelines for this ?

解决方案

For simple, unstructured datatypes such as Int or Double, turning them into strict fields is often a good default. That makes their space consumption very predictable (and constant). While it's possible that performance degrades due to performing unnecessary computations, this is, in general unlikely. For example, keeping track of a position is usually extremely simple and inexpensive, so there's nothing to be afraid of in terms of performance, and having predictable space behaviour is far more important.

An additional advantages of making simple types strict is that they can often be unpacked, i.e., stored directly within the constructor instead of via an additional indirection (there are pragmas or compiler flags for it). For small types, this usually is an advantage.

For structured datatypes such as lists or trees, the situation is far more complicated. A simple ! will rarely help here, because it only forces to WHNF. An evaluated list or tree can also easily be more costly in terms of space than an unevaluated thunk. Nevertheless, it sometimes makes sense to make such data strict as well. In such cases, you usually would wrap the constructor using a function (a so-called smart constructor) that establishes strictness invariants by calling deepseq in appropriate places.

这篇关于Haskell:使用严格性指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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