[Haskell-cafe] Handling platform- or configuration-specific code (or, my CPP complaints)

wren ng thornton wren at freegeek.org
Thu Sep 9 00:54:28 EDT 2010

On 9/7/10 3:10 PM, Ben Millwood wrote:
> So I wonder what people
> think of the use of CPP in Haskell code, what alternatives people can
> propose, or what people hope to see in future to make conditional
> compilation of Haskell code more elegant and simple?

The only thing I ever use CPP for in Haskell is top-level conditional 

* That is, say I have a function foo which has a vanilla Haskell 
definition, but also has a special definition for GHC performance 
hackery, or which needs a special definition on some compilers in order 
to correct compiler-specific bugs. I'll use #ifdef here to give the 
different versions. I'll also occasionally do this for things like 
choosing whether to use the FFI vs a native definition, for debugging 

* Another example is when using GeneralizedNewtypeDeriving in GHC, but 
still wanting to give normal definitions for other compilers to use.

* The only other example I can think of is when defining Applicative 
instances, since I only want to do that when linking against versions of 
base which are new enough to have it. Occasionally you can get similar 
issues re ByteString vs base.

In general, I think using CPP for actual macro processing is extremely 
poor style and can easily make code inscrutable (and no doubt 
bug-prone). If the Haskell spec were to add support for this sort of 
top-level compiler/compiletime-flag conditional definition, I'd switch over.

This matches the style in most of the code I've looked at. And it also 
means that the incompatibilities are localized and hidden from most 
client code. Depending on the nature of your library API conflict, if 
you can localize things into a few definitions of the core functions you 
use in the rest of your code, then that'd be best. But that's not always 
possible. I've yet to run into the case where I really need to support 
incompatible versions of a library when it's that closely integrated, so 
I don't have much advice there.

Live well,

More information about the Haskell-Cafe mailing list