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

Henning Thielemann lemming at henning-thielemann.de
Wed Dec 16 22:12:24 UTC 2020


On Wed, 16 Dec 2020, 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.

You could also use Num + Ord and do:

   sum $ takeWhile (<=n) $ iterate (1+) 1


More information about the Haskell-Cafe mailing list