I tried to solve Duplicate each element in a Haskell List task and make it as a full program, that write the list to standard output
Here is my solution
main :: IO () main = getList >>= return . doubleEachItem >>= putStrLn . show getList = return [1,3,5] doubleEachItem :: [Int] -> [Int] doubleEachItem = foldr (++) [] . map (take 2 . repeat)
But when I try to process really long list
getList = return . take 10000000000 $ repeat 15
the program terminated with out of memory error.
The question is: how I can improve the program, so it would be able to process lists of any size?
Edit:
I think program crashed because I run it with runghc
command. In that case ghc consume about 3Gbytes of memory and was killed by operating system. The output file after crash was only about 0.6GBytes. The reason of such behavior is unclear for me.
When I compile the program to native executable ghc haskell03.hs -o haskell03
and execute it with redirection to a file ./haskell03 >out03.txt
it perfectly runs in constant memory space and produces output file with speed about 20MBytes/sec. When the program finished the output file takes 57GBytes. Total execution time was 47 minutes.
foo >>= return . bar
is the same thing asfmap bar foo
. - luqui