patternMinor
Sum Arithmetic Progression in Haskell
Viewed 0 times
arithmeticprogressionhaskellsum
Problem
I am learning Haskell and as exercise I am doing Project Euler Problems. In this case PE1.
Now, off the bat I am shadowing the last function. How could I rename this variable along with first?
Is there any way I can improve readability? Any edge case or fail case I haven't covered? Any performance fail?
-- Sum any given finite Airthmetic Progression
sumAP :: Integer -> Integer -> Integer -> Integer
sumAP first limit step = do
let last = limit - (limit `rem` step)
let terms = (last - first) `quot` step + 1
let avg = first + last
terms * avg `quot` 2Now, off the bat I am shadowing the last function. How could I rename this variable along with first?
Is there any way I can improve readability? Any edge case or fail case I haven't covered? Any performance fail?
Solution
My first comment would be to comment your code.
You need documentation so I know what your function is meant to do. "Sum any given finite Arithmetic Progression" would suffice if you passed in an
I don't know what algorithm you're trying to use. You've evidently taken some maths for sums of arithmetic progressions and applied it to the problem, but there's no way for me to verify that the maths is correct or that the code implements it correctly without at least rudimentary explanation of what you did. I could reimplement it myself, but code should be verifiable much more easily than that.
You need documentation so I know what your function is meant to do. "Sum any given finite Arithmetic Progression" would suffice if you passed in an
ArithmeticProgression, but instead you pass in some bounds. Writing an arithmetic progression type would be simple and might even help a little, but you still need to document that.I don't know what algorithm you're trying to use. You've evidently taken some maths for sums of arithmetic progressions and applied it to the problem, but there's no way for me to verify that the maths is correct or that the code implements it correctly without at least rudimentary explanation of what you did. I could reimplement it myself, but code should be verifiable much more easily than that.
Context
StackExchange Code Review Q#94193, answer score: 5
Revisions (0)
No revisions yet.