简体   繁体   English

为什么GHC不能针对常数进行优化?

[英]Why is not GHC optimizing for constants?

import Data.List
a = foldl' (+) 0 [1..99999999]
main = putStrLn $ show $ a

This program takes a while to run. 该程序需要一段时间才能运行。 But a does not depend on anything and thus is constant. 但是a不依赖于任何东西,因此是不变的。 It could be perfectly calculated at compile time. 它可以在编译时完美计算。 Why is not GHC optimizing for this? 为什么不对GHC进行优化呢? Is there a flag for it to do so, or should I just replace that kind of constant calculation by the values themselves? 它是否有一个标志,或者我应该用值本身替换那种常量计算?

This is not a perfect solution, but as kqr already remarked you can of course achieve your goal with Template Haskell: 这不是一个完美的解决方案,但正如kqr已经说过的那样,你当然可以通过Template Haskell实现你的目标:

{-# LANGUAGE TemplateHaskell #-}

import Language.Haskell.TH
import Data.List

a :: Integer
a = $( return . LitE . IntegerL $ foldl' (+) 0 [1..99999999] )

main = print a

This generates the integer literal 4999999950000000 from the fold expression, before actually starting to compile the program. 在实际开始编译程序之前,这将从fold表达式生成整数文字4999999950000000

This is the same as the discussion covered by this reddit thread. 这与此reddit线程所涵盖的讨论相同。 Basically, what you want is but a simple case which is uncommon in practice. 基本上,你想要的只是一个在实践中不常见的简单案例。 Optimizing with constant folding quickly turns into problems regarding Gödel's theorem and the Halting problem. 通过恒定折叠进行优化很快就会成为关于哥德尔定理和停止问题的问题。

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

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