Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. It could be perfectly calculated at compile time. Why is not GHC optimizing for this? Is there a flag for it to do so, or should I just replace that kind of constant calculation by the values themselves?

like image 498
MaiaVictor Avatar asked Sep 08 '13 11:09

MaiaVictor


1 Answers

This is not a perfect solution, but as kqr already remarked you can of course achieve your goal with 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.

like image 84
leftaroundabout Avatar answered Oct 04 '22 02:10

leftaroundabout