I don’t know whether it is a valid term ‘lazy types’. But still, IO is lazy so in
import Control.Monad
import Data.List
result :: IO Double
result = foldl1' (liftM2 (+)) $ map return [1..10000000]
result' :: IO Double
result' = return $ foldl1' (+) [1..10000000]
result is slow and uses a lot of memory, unlike result'. How shall I fold [IO a] ?
resultconstructs one bigIO Doublevalue without evaluating any of the intermediate results, that only happens when the total result is demanded, e.g. for printing.foldl'evaluates the intermediate results to weak head normal form, that is, to the outermost constructor or lambda. Since (in GHC),IO ahas the constructorIO, the intermediate results of the fold have the formand the expression under the
IOgets more complicated at each step.To avoid that, you have to force not only the intermediate
IOvalues, but also the values that they return,works for your example.