The following works fine:
sdb n = sum [n,n*2..999]
main = print $ sdb 3 + sdb 5 - sdb 15
But it's not that efficient since it has to sum 999/n times each time sdb is called. when I rewrote sdb:
sdb n =
let x = quot 999 n
in n*x*(x+1)/2
and runhaskell
the whole code, I got an entire page of error. Summing it up:
... No instance for (Show a0) arising from a use of `print'
... No instance for (Integral a0) arising from a use of `sdb'
... No instance for (Num a0) arising from a use of `-'
I added type declaration for sdb:
sdb :: Integer -> Integer
but I got another error:
No instance for (Fractional Integer) arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the expression: n * x * (x + 1) / 2
In the expression: let x = quot 999 n in n * x * (x + 1) / 2
In an equation for `sdb':
sdb n = let x = quot 999 n in n * x * (x + 1) / 2
I don't get it.
What should I correct? Can you also explain why I got those errors? SOLVED: I changed
/
withdiv
.Is there a more idiomatic and/or concise way to write the same algorithm?