英文:
Recursive sumNumbers in Haskell
问题
findSum :: Int -> Int -> Int -> Int
findSum a b n
| a >= 0 && b > 0 && n > 3 = findSum1 a b n + findSum2 a b n + findSum3 a b n
| otherwise = 0
where
findSum1 :: Int -> Int -> Int -> Int
findSum1 a b n
| n <= 3 = 0
| otherwise = a + 2 ^ (n-1) * b + findSum1 a b (n-1)
findSum2 :: Int -> Int -> Int -> Int
findSum2 a b n
| n <= 3 = 0
| otherwise = a + 2 ^ (n-2) * b + findSum2 a b (n-2)
findSum3 :: Int -> Int -> Int -> Int
findSum3 a b n
| n < 0 = 0
| otherwise = a + 2 ^ (n-3) * b + findSum3 a b (n-3)
英文:
My task is: to write a function who calculate (a + 2^0 * b + 2^1 * b + 2^2 * b
until it happens 2^(n-1)*b)
, other who calculate (a + 2^0 * b + 2^1 * b + 2^2 * b
until it happens 2^(n-2)*b
) and another one who calculate (a + 2^0 * b + 2^1 * b + 2^2 * b
until it happens 2^(n-3)*b
).
I have to write a function who calculate sum of the three functions but this function has to accept 3 argument - the numbers a
b
n
!
n
is always greater than 3!
This is what I have done until this moment:
findSum :: Int -> Int -> Int -> Int
findSum a b n
| a >= 0 && b > 0 && n > 3 = findSum1 a b n + findSum2 a b n + findSum3 a b n
| otherwise = 0
where
findSum1 :: Int -> Int -> Int -> Int
findSum1 a b n
| n <= 3 = 0
| otherwise = a + 2 ^ (n-1) * b + findSum1 a b (n-1)
findSum2 :: Int -> Int -> Int -> Int
findSum2 a b n
| n <= 3 = 0
| otherwise = a + 2 ^ (n-2) * b + findSum2 a b (n-2)
findSum3 :: Int -> Int -> Int -> Int
findSum3 a b n
| n < 0 = 0
| otherwise = a + 2 ^ (n-3) * b + findSum3 a b (n-3)
But It gives me an error:
Exception: Negative exponent.
答案1
得分: 2
findSum3
在第一个条件中比较的是 n < 0
而不是 n <= 3
。
这导致它试图计算 2 ^ (n-3)
,而实际上 n < 3
,最终导致负指数,这是不允许的。
英文:
findSum3
does compare n < 0
instead of n <= 3
in the first clause.
That leads to it trying to calculate 2 ^ (n-3)
with an n < 3
eventually which results in a negative exponent, and that's not allowed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论