Haskell code to calculate the sum of squares of positive integers

Suppose it’s required to calculate the sum of squares of the positive numbers 1,2…n. In Haskell, it can be done using fold function or map function very easily. The code will be just a couple of lines long.

With foldr function

sumsq :: Int -> Int
sumsq n = foldr op 0 [1..n]
where op x y = x*x + y

With map function

sumsq1 :: Int -> Int
sumsq1 n = sum(map op [1..n])

The output of the above codes will look like this…

*Main> sumsq 4
30
*Main> sumsq1 4
30

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.