Using #if-#else-#endif in Haskell
I have 2 versions of the same program with only little changes between the two. Instead of having separate files, I use #if defined (PAR)
- #else
- #endif
and then compile with or without -cpp -DPAR
to switch between the 2 versions. I like this way as you only have to work on 开发者_如何学编程a single hs file. However, since my aim is to write parallel/optimised version of the original program, I wonder if using #if-#else#-endif
has any performance implication? Basically I would like an explanation of how this works under the hood. Thanks
#if defined(PAR)
import Control.Parallel
import Control.Parallel.Strategies
import Control.DeepSeq
#endif
#if defined(PAR)
test = sum ( map expensiveFunc myList `using` strat )
where strat = parListChunk 100 rseq
#else
test = sum ( map expensiveFunc myList )
#endif
Note:
Instead of the -cpp
flag, you could use the language options in your source file:
e.g. {-# LANGUAGE CPP #-}
But you still need to provide (or not) -Dxxx
when compiling in order to choose which part of the program the compiler should ignore ( where xxx is the defined variable in the hs file).
C preprocessor directives are in effect only during compilation. The compiler simply cuts out the lines within the #ifdef block and then compiles the program as usual, so there is no runtime performance penalty.
精彩评论