简体   繁体   English

编译时的顶级表达式评估

[英]Top-level expression evaluation at compile time

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]

If what you're evaluating is an instance of Lift , you can evaluate it at compile time using TemplateHaskell : 如果您正在评估的是Lift的实例,则可以使用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 : 如果需要,可以使用-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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM