Memory usage of constructors in haskell [duplicate]

心已入冬 提交于 2020-01-03 08:54:09

问题


Possible Duplicate:
Memory footprint of Haskell data types

When solving combinatorial problems, I will often represent the solution as a bit string, eg. 1010100010110111000110... You get the picture.

I figured that when I use [Int] for the bit string, Int always spends the same amount of memory, no matter how big the number actually is (because Int it's bounded, in contrast to Integer), as the computer only remembers the bit representation, and String's would take even more space as far as I know.

My idea was then to use the data type

data Bits = Empty | Zero Bits | One Bits deriving (Eq,Ord,Show)

But how much memory do the constructors Empty, Zero and One use compared to Int's?


回答1:


Int costs two words in memory (#I constructor and #Int field), your Bits data can use various cost, for example: Zero (One (Zero Empty)) will cost:

  1. One word for Empty constructor
  2. Two words for Zero Constructor and field
  3. Two words for One Constructor and field
  4. Two words for Zero Constructor and field

and total cost — 7 words. So memory amount for your data can be more than for Int.



来源:https://stackoverflow.com/questions/12245410/memory-usage-of-constructors-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!