Skip to content

Should sum and product be strict? Or have strict variants?

Currently sum and product are lazy according to the report. GHC matches the report, while hugs makes them strict. nhc98 recently made them strict, but reverted to lazy upon the report's definition being pointed out.

For most cases, such as summing a list of Ints or Integers, strict behaviour is desirable. Thus we propose that either sum and product are made strict (i.e. use foldl') or strict variants sum' and product' are made available as well.

Here is a program to demonstrate the difference:

import Data.List

data Foo = Zero | A | B | C
    deriving (Eq, Show)

instance Num Foo where
    _ + Zero = error "Adding Zero"
    _ + A = error "Adding A"
    _ + B = error "Adding B"
    _ + C = C
    fromInteger 0 = Zero

xs = [A, B, C]
 
f  = foldl  (+) 0 xs
f' = foldl' (+) 0 xs
s = sum xs

GHC and Haskell 98 say:

*Main> f
C
*Main> f'
*** Exception: Adding A
*Main> s
C
*Main>

while hugs and this proposal say:

Main> f
C
Main> f'
Program error: Adding A
Main> s 
Program error: Adding A
Main>
Trac metadata
Trac field Value
Version
Type Bug
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component HaskellPrime
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information