编译时的顶级表达式评估

Top-level expression evaluation at compile time

有什么方法可以确保在编译时对如下表达式进行求值吗?

myList :: [Int]
myList = sort [3,2,0,1]

如果您正在评估的是 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]))

如果你愿意,你可以用 -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]