Problem with a constant while implementing a function

Consider this code:
ex :: Integer->Integer->Integer
ex m n
| m>n = 0
| otherwise = (n+m)^k + ex(m+1) n
where k=m
I want to implement the sum (Σ) from i=m to n of (n+i)^m
I know that in the code above when ex(m+1)n is executed it changes the value of k as well because it is m.
How can I maintain the value of k ‘‘unchanged’’ while ex(m+1)n is executed? Is there a way to assign it inside the function to make it independent?

You can add another argument to ex:

ex :: Integer -> Integer -> Integer -> Integer
ex k m n
...

now you also need to pass the k to the recursive call and the where clause is unnecessary.

I would do it like this:

ex :: Integer -> Integer -> Integer
ex m0 n0 = ex' m0 n0 where
  k = m0
  ex' m n = ...

Where ex' is your original definition.

1 Like