如何强制严格评估一系列ByteString [英] How to force strict evaluation of a sequence of ByteString

查看:133
本文介绍了如何强制严格评估一系列ByteString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import Data.Sequence(Seq,length)
import Data .ByteString.UTF8(ByteString)

type StringSeq = Seq ByteString

I具有类型 StringSeq 的表达式,我想用 deepseq 强制执行严格的评估。所以我需要定义 NFData 的实例。我做了以下事情:

pre $ import Control.DeepSeq(NFData,deepseq)

实例NFData ByteString

实例NFData a => NFData(Seq a)其中
rnf s = rnf(长度s)

序列的长度来强制评估序列本身。这似乎工作,但这是正确的实施?有更好的吗?计算一个序列的长度是否会引入太多开销?计算长度是不够的,你需要计算正常形式的序列内容。我建议你使用来自 Control.Seq 的seqFoldable ,它允许你强制任何可折叠的结构。然后你可以简单地调用

  mySeq`使用`seqFoldable rdeepseq 

或定义

  instance NFData a => NFData(Seq a)其中
rnf = seqFoldable rdeepseq


I have the following Haskell type definition:

import Data.Sequence(Seq, length)
import Data.ByteString.UTF8(ByteString)

type StringSeq = Seq ByteString

I have expressions of type StringSeq for which I would like to force strict evaluation with deepseq. So I need to define instances of NFData. I did the following:

import Control.DeepSeq(NFData, deepseq)

instance NFData ByteString

instance NFData a => NFData (Seq a) where
  rnf s = rnf (length s)

So I compute the length of a sequence to force evaluation of the sequence itself. This seems to work but is this the correct implementation? Are there better ones? Does computing the length of a sequence introduce too much overhead?

解决方案

Computing length is not enough, you need to compute the normal forms of the content of a sequence. I suggest you to use seqFoldable from Control.Seq which allows you to force any foldable structure. Then you can call simply

mySeq `using` seqFoldable rdeepseq

or define

instance NFData a => NFData (Seq a) where
    rnf = seqFoldable rdeepseq

这篇关于如何强制严格评估一系列ByteString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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