[Haskell-cafe] Binary constants in Haskell

Henning Thielemann lemming at henning-thielemann.de
Thu Oct 25 15:41:27 EDT 2007


On Thu, 25 Oct 2007, Stefan O'Rear wrote:

> On Thu, Oct 25, 2007 at 02:40:36PM +0200, Josef Svenningsson wrote:
> > On 10/24/07, Neil Mitchell <ndmitchell at gmail.com> wrote:
> > >
> > > 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?

Generally I prefer to solve such problems within Haskell instead of
blowing up the language. If at all number literals are supported, then
that should be done in a consistent manner. E.g. in Modula-3 you write
2_10000, 8_20, 16_10, for a binary, octal, hexadecimal number.
 http://www.cs.tut.fi/lintula/manual/modula3/m3defn/html/numbers.html
   I can't remember that I ever used this feature, because Modula-3 has
much better support for bit oriented data, namely bit sets. In Haskell we
could achieve the same with an appropriate library.
  (bin "11002000") would not yield a compile time error, but due to its
seldom usage this might be ok. I vote for this approach.

> 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.

I hoped GHC did this all the time. :-(

> 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.

Agreed!

> Total functions, full laziness, and compile time evaluation of finite
> non-bottom CAFs...

If I write a program that approximates a big but fixed number of digits of
Pi - how can we prevent the compiler from computing Pi, and generating a
program which contains just the digits of Pi as constant data?


More information about the Haskell-Cafe mailing list