I'm new to Haskell, and I'm wondering why my programs are so slow compared to other languages.
Haskell, 6 seconds (x64, -O2):
nextCollatz :: Int -> Int
nextCollatz x = if even x
then quot x 2
else 3 * x + 1
collatzLength :: Int -> Int
collatzLength x = if x == 1
then 0
else 1 + collatzLength (nextCollatz x)
main = print . show . sum . map collatzLength $ [1..3000000]
Julia, 0.8 seconds (excluding the compilation time):
function main()
sum = 0
for i = [1:3000000]
while i > 1
i = isodd(i) ? 3 * i + 1 : i >> 1
sum += 1
end
end
sum
end
println(main())
Maybe the comparison isn't fair, but I'd like to know how to improve my Haskell code to bring it on par with other high-level languages such as Julia and JavaScript.
While memoization and parallelization would definitely help, currently I'm concerned with efficient iteration and arithmetic.