强制预先计算常量 [英] Force pre-computation of a constant

查看:141
本文介绍了强制预先计算常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Haskell中有一个常量声明 - 我能否提前对它进行评估?我看到一些代码看起来很粗糙,

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

需要时间当我分析它时(它确实有168M的调用)时, fst 调用。 myList 的二进制表示非常小,例如可以复制到全局内存中(如果这是一个C程序)。我正在编译 -O3 -optc-O3 当然。

非常感谢!



为一个自定义类型生成Lift实例

赋予 lift call in sclv的答案必须是Lift的一个实例。有一个名为 th-lift 的库,它将为自定义数据类型生成Lift实例。查看该软件包的文档

解决方案

使用Template Haskell生成编译时常量:

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

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

lift 需要一个Haskell值并将其提升到TH Exp。 $()运行封闭的引号,并在编译时将生成的exp拼接到代码中。


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.

解决方案

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.

这篇关于强制预先计算常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆