I am solving some problems of Project Euler in Haskell. I wrote a program for a riddle in it and it did not work as I expected.
When I looked in the task manager when running the program I saw that it was using > 1 gigabyte of RAM on ghc. A friend of me wrote a program with the same meaning in Java and succeeded in 7 seconds.
import Data.List
opl = find vw $ map (\x-> fromDigits (x++[0,0,9]) )
$ sequence [[1],re,[2],re,[3],re,[4],re,[5],re,[6],re,[7],re,[8],re]
vw x = hh^2 == x
where hh = (round.sqrt.fromIntegral) x
re = [0..9]
fromDigits x = foldl1 (\n m->10*n+m) x
I know this program would output the number I want given enough RAM and time, but there has to be a better-performing way.
The main problem here is that sequence has a space leak. It is defined like this:
so the problem is that the list produced by the recursive call
sequence xssis re-used for each of the elements ofxs, so it can’t be discarded until the end. A version without the space leak isPS. the answer seems to be
Just 1229314359627783009Edit version avoiding the concat:
note that both of these versions generate the results in a different order from the standard
sequence, so while they work for this problem we can’t use one as a specialised version ofsequence.