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?
Share
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
fiband then splicingOriginal 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.
and
To confirm that the work is performed at compile-time, we can compile with
-ddump-simplto see the core, which confirms it.