Skip to content

Instantly share code, notes, and snippets.

@MgaMPKAy
Created May 17, 2012 06:06
Show Gist options
  • Save MgaMPKAy/2716873 to your computer and use it in GitHub Desktop.
Save MgaMPKAy/2716873 to your computer and use it in GitHub Desktop.
Calculate fib n in compile time with TemplateHaskell
{-# LANGUAGE TemplateHaskell #-}
module Fib where
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
fib' :: Int -> Int
fib' n
| n <= 2 = 1
| otherwise = fib' (n - 1) + fib' (n - 2)
fib :: Int -> Q Exp
fib n = [| $(lift $ fib' n) |]
-- more : http://stackoverflow.com/questions/9243794/evaluating-a-function-at-compile-time-with-template-haskell
{-# LANGUAGE TemplateHaskell #-}
import Fib
main = print $(fib 40){-# LANGUAGE TemplateHaskell #-}
import Fib
main = print $(fib 40)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment