Data.Foldable.foldr1 too strict

Brent Yorgey byorgey at seas.upenn.edu
Thu Sep 27 16:09:07 CEST 2012


On Thu, Sep 27, 2012 at 12:21:32AM +0200, Henning Thielemann wrote:
> 
> 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

Isn't that still too strict?  I would expect to see "abcdef" before
the exception.

-Brent



More information about the Libraries mailing list