Generate successive matrix powers and take cumulative sums using matrix addition:For the stipulated square matrix,
seriesMat :: Num a => Matrix a -> [Matrix a]
seriesMat m = scanl1 addMat (iterate (multMat m) m)iterate (multMat m) m produces m, m*m, m*(m*m), and so on. Associativity of exact matrix multiplication identifies these as . The left scan scanl1 addMat then returnsAll dimensions remain compatible. The infinite outer list is available a finite prefix at a time under lazy evaluation; no convergence of the matrix geometric series is needed. With floating-point entries, the expression specifies this particular multiplication and addition order, since machine arithmetic need not obey the exact algebraic laws.The most general type signature is
scanl :: (b -> a -> b) -> b -> [a] -> [b]. The left fold step consumes an accumulator of type b and an input of type a, returning the next accumulator. A left scan retains all these accumulator values, including the initial one.foldl f e (x:ys) = foldl f (f e x) ysFor the empty list, the prefix definition immediately gives
scanl f e [] = [e]. For a nonempty list, calculate:scanl f e (x:xs)
= map (foldl f e) ([] : map (x:) (inits xs))
= e : map ((foldl f e) . (x:)) (inits xs)
= e : map (foldl f (f e x)) (inits xs)
= e : scanl f (f e x) xsThe second-to-third line uses the displayed fold equation as an equality of functions of
ys. Hence the efficient left scan is:scanl :: (b -> a -> b) -> b -> [a] -> [b]
scanl f e [] = [e]
scanl f e (x:xs) = e : scanl f (f e x) xsOn a finite input of length , fully demanding the original prefix-fold results performs accumulator updates. The recurrence performs . Thus the update count improves from to , assuming constant-cost updates. Both return results. This does not assert constant space for arbitrary accumulators or imply that lazy accumulators are evaluated strictly.