s1 ~ sum $ map (sum . flip map [0..n] . gcd) [0..n]<div><div>s2 ~ sum $ concatMap (flip map [0..n] . gcd) [0..n] </div><div><br></div><div>There are some posts from <span style="font-family:'Times New Roman';background-color:rgb(255,255,255);font-size:medium">Joachim Breitner investigated fusion for concatMap:</span></div>
<div><a href="http://www.haskell.org/pipermail/haskell-cafe/2011-December/thread.html#97227">http://www.haskell.org/pipermail/haskell-cafe/2011-December/thread.html#97227</a></div><div><br></div><div><br></div><div><div><br>
<div class="gmail_quote">2012/6/25 Johannes Waldmann <span dir="ltr"><<a href="mailto:waldmann@imn.htwk-leipzig.de" target="_blank">waldmann@imn.htwk-leipzig.de</a>></span><br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Dear all,<br>
<br>
while doing some benchmarking (*)<br>
I noticed that function s1 is considerably faster than s2<br>
(but I wanted s2 because it looks more natural)<br>
(for n = 10000, s1 takes 20 s, s2 takes 13 s; compiled by ghc-7.4.2 -O2)<br>
<br>
s1 :: Int -> Int<br>
s1 n = sum $ do<br>
x <- [ 0 .. n-1 ]<br>
return $ sum $ do<br>
y <- [ 0 .. n-1 ]<br>
return $ gcd x y<br>
<br>
s2 :: Int -> Int<br>
s2 n = sum $ do<br>
x <- [ 0 .. n-1 ]<br>
y <- [ 0 .. n-1 ]<br>
return $ gcd x y<br>
<br>
I was expecting that in both programs,<br>
all lists will be fused away (are they?)<br>
so the code generator essentially can produce straightforward<br>
assembly code (no allocations, no closures, etc.)<br>
<br>
<br>
For reference, I also wrote the equivalent imperative program<br>
(two nested loops, one accumulator for the sum)<br>
(with the straightforward recursive gcd)<br>
and runtimes are (for same input as above)<br>
<br>
C/gcc: 7.3 s , Java: 7.7 s, C#/Mono: 8.7 s<br>
<br>
<br>
So, they sort of agree with each other, but disagree with ghc.<br>
Where does the factor 2 come from? Lists? Laziness?<br>
Does ghc turn the tail recursion (in gcd) into a loop? (gcc does).<br>
(I am looking at -ddump-asm but can't quite see through it.)<br>
<br>
<br>
(*) benchmarking to show that today's compilers are clever enough<br>
such that the choice of paradigm/language does not really matter<br>
for this kind of low-level programming.<br>
<br>
<br>
<br>
<br>
<br>
<br>
_______________________________________________<br>
Haskell-Cafe mailing list<br>
<a href="mailto:Haskell-Cafe@haskell.org">Haskell-Cafe@haskell.org</a><br>
<a href="http://www.haskell.org/mailman/listinfo/haskell-cafe" target="_blank">http://www.haskell.org/mailman/listinfo/haskell-cafe</a><br>
</blockquote></div><br></div></div></div>