[Haskell-cafe] "Natural" polymorphism for n*(n+1)/2

MigMit migmit at gmail.com
Wed Dec 16 22:17:30 UTC 2020


A small optimization, maybe: fromInteger ((n * (n+1)) `div` 2)?

> On 16 Dec 2020, at 23:13, Jaro Reinders <jaro.reinders at gmail.com> wrote:
> 
> Num alone is enough: sum [1..n] = sum (map fromInteger [1..n])
> 
> On 12/16/20 11:07 PM, MigMit wrote:
>> Num + Enum would be enough though, since n*(n+1)/2 = sum [1..n], n*(n+1)*(n+2)/6 = sum (map (\m -> sum [1..m]) [1..n]) etc. Not quite effective, of course.
>>> On 16 Dec 2020, at 22:57, David Feuer <david.feuer at gmail.com> wrote:
>>> 
>>> I very much doubt that Num a is sufficient. That's not even enough to check whether a number is even. You can certainly perform the calculation with `Integral a`, but you'll have to apply some external reasoning to see that the result is correct.
>>> 
>>> On Wed, Dec 16, 2020, 4:45 PM M Douglas McIlroy <m.douglas.mcilroy at dartmouth.edu> wrote:
>>> Some nominally rational functions, e.g n*(n+1)/2,
>>> yield integer values for integer arguments. I seek
>>> either a way to wrap such a function so it has type
>>> Num a => a->a or a convincing argument that it can't
>>> be done.
>>> 
>>> Doug
>>> _______________________________________________
>>> Haskell-Cafe mailing list
>>> To (un)subscribe, modify options or view archives go to:
>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
>>> Only members subscribed via the mailman list are allowed to post.
>>> _______________________________________________
>>> Haskell-Cafe mailing list
>>> To (un)subscribe, modify options or view archives go to:
>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
>>> Only members subscribed via the mailman list are allowed to post.
>> _______________________________________________
>> Haskell-Cafe mailing list
>> To (un)subscribe, modify options or view archives go to:
>> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
>> Only members subscribed via the mailman list are allowed to post.
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.



More information about the Haskell-Cafe mailing list