[Haskell-cafe] Small question

Andrew Coppin andrewcoppin at btinternet.com
Thu Aug 9 17:19:59 EDT 2007

Stefan O'Rear wrote:
> On Thu, Aug 09, 2007 at 09:27:23PM +0100, Andrew Coppin wrote:
>> OOC, in what way is Bool not "primitive enough"? You mean because it's an 
>> algebraic data type, rather than a bunch of bits in the machine? For that 
>> matter, just how much space does such a type typically use?
> Yes.
> data Bool = False | True
> In general, GHC doesn't do "unboxing".  Instead it has a simpler and
> more general approach, where it passes the fields of a
> single-constructor type instead of the type itself; this is as good as
> true unboxing in most of the interesting cases:
> data Int = I# Int#
> data Float = F# Float#
> data Double = D# Double#
> data Char = C# Char#
> data Ptr = Ptr Addr#
> ...

I see. (I think!)

> but not always:
> data Bool = False | True
> data Integer = S# Int# | J# ByteArray# Int#
> As far as actual heap usage goes, GHC creates single static values for
> all 0-argument constructors; so all Bool WHNFs are one of two addresses,
> one for True and one for False.  But GHC isn't quite smart enough for
> the -funbox-strict-fields mechanism to understand this...

Right. So a Bool is a 32 or 64 bit quantity. (Rather like Smalltalk...)

That presumably means that a (Double,Double) is going to be a thunk that 
evaluates to a (,) pointing to two thunks that evaluate to pointers... 
IOW, something like 3 pointers' worth of space. Whereas my Quad object 
is going to be a pointer to one of 4 values... so it looks like Quads 
save space. (And they're more strict.) OTOH, I'm not sure what the time 
penalty is like...

It would be nice if there were some general mechanism for turning a 
bunch of Bool flags into a single machine word. E.g., if I did a

  data Foo = Foo {flagX, flagY, flagZ :: !Bool}

and it ends up that a Foo value is just a single machine word, and GHC 
picks which bit each flag is... I guess if you want that at present 
you'd have to code it all by hand. Hmm, I think this might work out 
better than my current Quad thing... I could do something like

  type Quad = Word8

  foo q = let
    x = if testBit 0 q ...
    y = if testBit 1 q ...

That should be quite fast... (?)

>> (Questions, questions, so many questions...)
> I like answering them. :)

Heh. I'll have to pester you more often. :-P

PS. Somewhere they should write a page entitled "Optimisations that GHC 
does (and doesn't) do"...

PPS. Hmm. Might be out of date fast? ;-)

More information about the Haskell-Cafe mailing list