9

Is there any way to ensure, that an expression like the following would be evaluated at compile time?

myList :: [Int]
myList = sort [3,2,0,1]
lanskey
  • 457
  • 3
  • 13
  • 2
    You can check the generated Core to see if that optimization was performed. But, AFAIK, there is no way to force that. – chi Jul 09 '16 at 13:21

1 Answers1

9

If what you're evaluating is an instance of Lift, you can evaluate it at compile time using TemplateHaskell:

{-# LANGUAGE TemplateHaskell #-}

module Sort where

import Data.List
import Language.Haskell.TH.Syntax

myList :: [Int]
myList = $(lift (sort [3,2,0,1] :: [Int]))

If you want, you can check what it has compiled to with -ddump-splices:

$ ghc -ddump-splices sort
[1 of 1] Compiling Sort             ( sort.hs, sort.o )
sort.hs:9:12-41: Splicing expression
    lift (sort [3, 2, 0, 1] :: [Int]) ======> [0, 1, 2, 3]
cchalmers
  • 2,896
  • 1
  • 11
  • 11