# Haskell Snippet – Summing series

Say I wanted to calculate something like $\displaystyle\sum_{i=10}^{40} r^2 - r -1$

 > sum[r^2-r-1|r<-[10..40]] 21049 

This can be generalised to something like the following:
 sumseries what from to = sum[what n|n<-[from..to]] 

Example:
 > sumseries (\r->r^2) 1 10 385 > sumseries (\r->r^2-r-1) 10 40 21049 

On paper, I’d have to

• split this into two sums: $\displaystyle\sum_{i=1}^{40} (r^2 - r -1) - \sum_{i=1}^{9} (r^2 - r -1)$
• find an expression for $\displaystyle\sum_{i=1}^{n} (r^2 - r -1)$ using standard sums of the first n squares and naturals, giving $\displaystyle\sum_{i=1}^{n} (r^2 - r -1) = \frac{1}{3}(n-2)n(n+2)$
• substitute n = 40 and n = 9 into this, and subtract the latter from the former