[Haskell-cafe] Course-of-value recursion by defining a sequence as a self-referential infinite list

Douglas McIlroy douglas.mcilroy at dartmouth.edu
Sat Feb 8 23:09:48 UTC 2025


>> Karczmarczuk’s solution via the Haskell prelude:
>>
>> part = 1 : b 1
>>   where b n = (1 : b (n + 1)) + (replicate n 0 ++ b n)
>>

> This is broken code, no?, just 2 reasons I can spot why:
> - function 'b n' calls 'b n' unconditionally (infite loop)
> - What is the reutrn type of 'b'? It seems like it returns list, but the
 >  return value is in the form 'a + b' , where (+) is instance of num so
 >  I don't think prelude contains any ad-hoc definition of (+) that
 >  returns list

Not broken, just insufficiently documented.  "part "is supposed to produce
an infinite stream whose nth element is the number of distinct
representations of n as a sum of positive integers.

The "infinite loop"  is deliberate, quite like
    ones = 1 : ones
which generates an infinite sequence of 1s.

It is not stated, but the (+) is understood to have been overloaded to
handle lists of Nums in the natural way

Doug
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20250208/a31dec26/attachment.html>


More information about the Haskell-Cafe mailing list