How to set initial conditions for a recursive function with two parameters (Haskell)

I work through Learn You a Haskell For Great Good and tried to work on some examples of problems for the recursion chapter.

I am trying to write a function that takes the lower bound "a" and the upper bound "b" and returns the sum of all numbers between, inclusive.

I initially tried (what I thought) a straightforward approach

sumInts :: Int -> Int -> Int
sumInts a a = a 
sumInts a b = (sumInts (a) (b-1)) + b

When I tried to compile, I received an error message

• Conflicting definitions for a

In the end, I just wanted this to work, so I split what should have been a single function into two parts.

sumInts' :: Int -> Int
sumInts' 0 = 0
sumInts' a = sumInts' (a-1) + a


sumInts :: Int -> Int -> Int
sumInts 0 b = sumInts' b 
sumInts a b = (sumInts (a-1) (b)) - (a-1)

I tried to find what you think is a pretty simple problem. Alas, it seems too niche to achieve results.

, ? , ? , ? !

+4
2

Haskell . , ( ). , :

sumInts a a = a

. :

sumInts :: (Num a, Ord a) => a -> a -> a
sumInts a b | a <= b = a + sumInts (a+1) b
            | otherwise = 0

(|). (=). otherwise True.

+3

, , - , .

sumInts :: Int -> Int -> Int
sumInts a b = ((a + b) / 2) * (b - a + 1)
0

Source: https://habr.com/ru/post/1685373/


All Articles