You can examine the code that GHC generates with -ddump-asm
.
Compile this program:
main = print $ 1.0 / fromIntegral (sum [(1::Int)..12345])
with:
$ ghc -O2 Main.hs -ddump-asm > asm-output
Then have a look at asm-output
, search for 12345
and you will see this loop:
_c47b:
addq %r14,%rsi
incq %r14
_c476:
cmpq $12345,%r14
jne _c47b
This shows that the list [1..12345]
is not actually created.
Update
It seems you intended to sum the reciprocals of the triangular numbers,
i.e. 1/1 + 1/3 + 1/6 + ... That is, you intended to write:
sum += 1.0 / (double) n;
This can be expressed in Haskell as:
main = print $ sum $ map (\x -> 1 / (fromIntegral x)) $ scanl (+) 1 [(2::Int)..12345]
Examining the generated assembly we see again that no intermediate list is created:
_c4ao:
cvtsi2sdq %rsi,%xmm0
movsd _n4aP(%rip),%xmm2
divsd %xmm0,%xmm2
addsd %xmm2,%xmm1
incq %r14
_c4ad:
addq %r14,%rsi
cmpq $12345,%r14
jne _c4ao
Here %r14
is the counter i
in your C code, %rsi
is the variable n
and %xmm1
is the accumulator sum
.