Data.Foldable.foldr1 too strict

Henning Thielemann lemming at henning-thielemann.de
Thu Sep 27 00:21:32 CEST 2012


I found that the default implementation of foldr1 in Data.Foldable is too 
strict (and foldl1, too). It always evaluates the complete spine of an 
input list:

-- taken from base-4.6:Data.Foldable.foldr1
foldr2 f xs = fromMaybe (P.error "foldr1: empty structure")
                 (Fold.foldr mf Nothing xs)
   where mf x Nothing = Just x
         mf x (Just y) = Just (f x y)

-- lazier version, only evaluates one item ahead
foldr3 f xs = fromMaybe (P.error "foldr1: empty structure")
                 (Fold.foldr mf Nothing xs)
   where mf x = Just . maybe x (f x)


*Data.NonEmpty> foldr2 (P.++) $ "abc" : "def" : P.undefined
"*** Exception: Prelude.undefined

*Data.NonEmpty> foldr3 (P.++) $ "abc" : "def" : P.undefined
"abc*** Exception: Prelude.undefined



More information about the Libraries mailing list