That code is not that slow for me. It takes about 200 ms on my computer (even in GHCi it takes only about 500 ms). You can make it slightly faster by compiling with optimisations ghc -O ...
and using Int
instead of the default Integer
:
k = [2300000, 2299999.. 1 :: Int]
(You only need a change there, the rest will be inferred automatically)
But those two optimisations only speed it up from 220 ms to 170 ms.
That’s fine, but the variable names are not very descriptive. If you want to avoid names I’d just write it all in one expression:
main = print $ sum $ take 535 $ sort $ map (+ 100) [2300000, 2299999 .. 1]
I thought using unboxed vectors might be faster, so I tried this code:
import qualified Data.Vector as Vector
import qualified Data.Vector.Algorithms.Intro as Vector
main :: IO ()
main =
print a
where
k = Vector.enumFromStepN (2300000 :: Int) (-1) 2300000
b = Vector.map (+100) k
c = Vector.take 535 $ Vector.modify Vector.sort b
a = Vector.sum c
But that takes 2.5 seconds. So a big win for laziness I’d say.
(But note that these are still immutable vectors, so this code probably creates a few copies of the whole array. You could optimise that even further, but that takes some skill and effort.)
Edit: changing from Intro
sort to Tim
sort makes it a lot faster, only taking 410 ms.