[Haskell-cafe] how to Enumerate without lists?

Johannes Waldmann johannes.waldmann at htwk-leipzig.de
Tue Sep 4 17:00:05 UTC 2018

Dear Cafe (again),

I was trying to write

  sum $ map (^ 2) $ [ 1 :: Int .. 10^8 ]

in a list-free style

   getSum $ foldMap  (Sum . (^ 2)) $ [ 1 :: Int .. 10^8 ]

This avoids building an intermediate list (of squares)
but it will allocate, since  foldMap  uses  foldr
(by default, and it's not overridden for lists)

The conclusion would be: not to use lists at all.
Which will be the point of my talk anyway.

But here, we get a list from  enumFromTo. Can we avoid that?

Let's try: we just reify  enumFromTo

  data Enumerator a = Enumerator {from :: a, to :: a}

we have this for decades, it is called  (a,a)  in Data.Ix,
and then

  instance Foldable Enumerator where ...

Oh no,  foldMap  (and others) would need an Enum constraint!

- J

More information about the Haskell-Cafe mailing list