Force pre-computation of a constant

喜你入骨 提交于 2019-12-03 10:03:51

问题


I have a constant declaration in Haskell -- can I force this to be evaluated ahead of time? I'm seeing some code that looks roughly like,

myList = [(a, b), (c, d)]
...
map (f . fst) myList

take time in the fst call when I profile it (it does have 168M calls). The binary representation of myList is quite small, and could be, for example, copied into global memory [if this were a C program]. I'm compiling with -O3 -optc-O3 of course.

Thanks very much!

Generating Lift instances for a custom type

Any expression given to the lift call in sclv's answer must be an instance of Lift. There's a library named th-lift which will generate Lift instances for custom data types. See that package's documentation.


回答1:


Generating a compile-time constant using Template Haskell:

{-# LANGUAGE TemplateHaskell #-}
import Language.Haskell.TH.Syntax(Lift(..))

test = $(lift $ (map (*20) [0..100] :: [Int]))

lift takes a Haskell value and lifts it into a TH Exp. The $() runs the enclosed quote, and splices the generated exp into the code at compile time.



来源:https://stackoverflow.com/questions/6122287/force-pre-computation-of-a-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!