I'm new to Haskell. Given the whole premise of Haskell is that a function will always return the same value, I'd expect there to be some way of e.g. calculating fibonacci values of constants at compile time, like I can do in C++ with template metaprogrmming, but I can't see how to do it. Is there a way?

@C.A.McCann Does it work for fibs though? My understanding was that TH was more like C macros, but that could be completely wrong. (That said, template C++ is kind of just glorified macros, and hmm I guess it might be possible to define fibs in C at compile time just via macros, not sure...) Anyway, concrete example would help.
–
lobsterismDec 29 '12 at 2:37

4

TH is arbitrary Haskell code, executed at compile time, that can generate syntax trees to splice definitions, expressions, or whatever else into the code. C macros don't even begin to compare. It's nowhere near as limited as C++ template junk is, it's just kind of a pain to use for anything non-trivial because working with the AST data types is clumsy.
–
C. A. McCannDec 29 '12 at 2:40

1

I've found it's very similar to how Lisp macros would feel if Lisp had actual syntax
–
jozefgDec 29 '12 at 12:24

2 Answers
2

edit: Daniel Fischer points out that you can lift an ordinary expression into Template Haskell and evaluate the result at compile-time, subject to certain constraints on the output type, by having an ordinary function fib and then splicing

$(let x = fib 1000 in [|x|])

Original answer follows.

As pointed out in comments, Template Haskell is the way to go for this. For inductive functions like fibonacci, it's fairly straightforward. You write code similar to a standard definition, but returning an ExpQ value. Due to splicing restrictions, you'll need to use 2 modules.

Well, kind of, but it seems rather trial-and-error (albeit organizedly-so) rather than directly deterministic. C++ templates are more the latter; WYSIWYG, and I was hoping for more of that kind of solution.
–
lobsterismDec 29 '12 at 3:35

@lobsterism Then you want Template Haskell. I only mentioned this solution because you were asking about why we can't take advantage the purity of functions to pre-compile them. However, Template Haskell does not take advantage of purity at all and it can even have side effects.
–
Gabriel GonzalezDec 29 '12 at 14:04