[Haskell-cafe] Binary constants in Haskell

Stefan O'Rear stefanor at cox.net
Thu Oct 25 12:21:49 EDT 2007


On Thu, Oct 25, 2007 at 02:40:36PM +0200, Josef Svenningsson wrote:
> On 10/24/07, Neil Mitchell <ndmitchell at gmail.com> wrote:
> > Hi
> >
> > > > Are there binary constants in Haskell, as
> > > > we have, for instance, 0o232 for octal and
> > > > 0xD29A for hexadecimal?
> > >
> > > No, though it is an interesting idea.
> >
> > You can get pretty close with existing Haskell though:
> >
> > (bin 100010011)
> >
> > where bin :: Integer -> Integer, and is left as an exercise for the
> > reader. Obviously its not as high performance, as proper binary
> > literals, but if you write them as top-level constants, they'll only
> > be computed once and shouldn't end up being in the performance
> > critical bits.
> >
> To make it efficient you could use Template Haskell and have the bin
> function generate the constant which could then be spliced in. I
> suppose it would look something like:
> $(bin 100010011)

Eek.  Template Haskell is massive overkill for this, and requires that
every syntax author muddle with syntax trees.  The Right Way to handle
this is constant folding of user defined functions; although I'm not
sure what form such a mechanism would take.  Perhaps a pragma FOLD 1
saying that this function should always be inlined if the first argument
is ground?

Lack of general constant folding is a serious problem with GHC.  Much
overly-slow numerics code is due to x^2, which loops over the bitwise
structure of 2 each time.  If (^) was marked FOLD 2, then we would get
(after a small amount of the compiler's usual symbolic manipulations) x
* x.

Bitwise operations are not folded even if both arguments are ground.
This would require a few primitive rules for xorInt# and friends, but
you'd also need something like FOLD to bypass the checks in shiftR etc.

Perhaps some kind of termination analysis (well founded recursion on
presburger arithmetic could certainly handle (^) and bin, no clue how
hard something like that is to implement) is in order.

I see an alarming trend towards ad-hoc transformation patterns and
excessive use of syntactic abstraction, when we should just be using
Haskell's rich semantic structure.  Total functions, full laziness, and
compile time evaluation of finite non-bottom CAFs...

Stefan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20071025/2d94e8d4/attachment.bin


More information about the Haskell-Cafe mailing list