我们可以在Haskell中编写一个函数来测量n个字符的字符串占用的字节数吗? [英] Can we write a function in Haskell to measure the number of bytes that a string of n characters occupies?

查看:77
本文介绍了我们可以在Haskell中编写一个函数来测量n个字符的字符串占用的字节数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有字符串

"abc"

,我想计算它在内存中占用的字节数。

and I want to calculate the number of bytes it occupies in memory.

我可以这样做:

import Data.Bits
finiteBitSize ("abc" :: [Char])

但由于 [Char] 不是该函数支持的类型。 (也是位而不是字节,但重点是画一张我要寻找的图片)。

but that breaks because [Char] is not a type supported by the function. (Also it is bits not bytes, but the point was to paint a picture of what I'm looking for).

我的问题是:我们可以在Haskell中编写一个函数来测量n个字符字符串占用的字节数吗?

推荐答案

有一个称为 ghc-datasize 的Haskell软件包,可用于计算 real 占用的内存。您甚至可以在官方Hackage文档中看到有关如何计算字符串大小的示例:

There's a Haskell package called ghc-datasize which allows you to calculate real occupied memory by every Haskell value. You can even see an example of how to calculate string size in the official Hackage documentation:

  • http://hackage.haskell.org/package/ghc-datasize

要计算 String 的长度,您需要使用以下函数:

To calculate the length of the String you need to use the following function:

recursiveSize :: a -> IO Word

它看起来像这样:

ghci> recursiveSize $!! "foobar"
240

这篇关于我们可以在Haskell中编写一个函数来测量n个字符的字符串占用的字节数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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