Recursive sumNumbers in Haskell

huangapple go评论57阅读模式
英文:

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 -&gt; Int -&gt; Int -&gt; Int
findSum a b n
  | a &gt;= 0 &amp;&amp; b &gt; 0 &amp;&amp; n &gt; 3 = findSum1 a b n + findSum2 a b n + findSum3 a b n
  | otherwise = 0
  where
    findSum1 :: Int -&gt; Int -&gt; Int -&gt; Int
    findSum1 a b n
      | n &lt;= 3 = 0
      | otherwise = a + 2 ^ (n-1) * b + findSum1 a b (n-1)

    findSum2 :: Int -&gt; Int -&gt; Int -&gt; Int
    findSum2 a b n
      | n &lt;= 3 = 0
      | otherwise = a + 2 ^ (n-2) * b + findSum2 a b (n-2)

    findSum3 :: Int -&gt; Int -&gt; Int -&gt; Int
    findSum3 a b n
      | n &lt; 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 &lt; 0 而不是 n &lt;= 3
这导致它试图计算 2 ^ (n-3),而实际上 n &lt; 3,最终导致负指数,这是不允许的。

英文:

findSum3 does compare n &lt; 0 instead of n &lt;= 3 in the first clause.
That leads to it trying to calculate 2 ^ (n-3) with an n &lt; 3 eventually which results in a negative exponent, and that's not allowed.

huangapple
  • 本文由 发表于 2023年3月12日 18:15:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75712434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定