[Haskell-cafe] curious about sum
jochem at functor.nl
Sat Jun 13 11:50:05 EDT 2009
Daniel Fischer wrote:
> Am Samstag 13 Juni 2009 17:00:36 schrieb Jochem Berndsen:
>> Deniz Dogan wrote:
>>> 2009/6/13 Jochem Berndsen <jochem at functor.nl>:
>>>> Keith Sheppard wrote:
>>>>> Is there any reason that sum isn't strict? I can't think of any case
>>>>> where that is a good thing.
>>>>> Prelude> sum [0 .. 1000000]
>>>>> *** Exception: stack overflow
>>>> It is useful if the (+) is nonstrict; although I cannot think of any
>>>> useful mathematical structure where (+) would be nonstrict.
>>> I remember needing a non-strict sum at least once, but I do not
>>> remember the exact application. But imagine having a (very) long list
>>> of numbers and you want to do A if the sum exceeds a small number,
>>> otherwise B.
>>> if sum [0..100000] > 10 then A else B
>>> However, this idea didn't work, because of strictness.
>> You can only do such things if you know that all entries of your list
>> are nonnegative. That requires a custom solution anyway (not to mention
>> the fact that to determine whether x > 10 or not, we need to explicitly
>> compute x).
> Well, if you have lazy Peano numbers of any kind, you know that all entries are non-
> negative and you needn't evaluate x fully to determine whether it's > 10. Isn't that the
> point why one would use lazy numbers at all?
Yes. (That's what I meant with 'custom solution', using Peano numbers
instead of Ints or Integers.)
Jochem Berndsen | jochem at functor.nl
More information about the Haskell-Cafe