1

I want to calculate the following sum in Haskell: (m + i)^n from i = m to n. So far I have thought of this:

sum2017 m n 
|m > n = 0
|otherwise = (c + m)^n + sum2017 (m+1) n
where c = m

but the problem is that c changes every time due to getting assigned a new value from recursive calls

2 Answers 2

5

You can stuff the actual recursion in a local function, keeping the c binding outside:

sum2017 m = go m
 where go μ n
        | μ > n     = 0
        | otherwise = (c + μ)^n + go (μ+1) n
       c = m

...of course, you may then omit the c = m entirely and just use (m + μ)^n in the recursion.

This specific example can also easily be done without any manual recursion at all, like

sum2017 m n = sum [(m+μ)^n | μ<-[m..n]]
Sign up to request clarification or add additional context in comments.

Comments

1

In Haskell, you want to avoid explicit recursions as much as possible.

So what do you do instead? You use looping function that does it for you ;)

sum2017 m n = sum $ ((^ n) . (+ m)) <$> [m .. n]

Or you could use lambda functions instead of this pointfree: (\x -> (c + x) ^ n)

If you decide to have a local function as leftaroundabout suggested, makes it recurse on itself, not on the global function:

sum2017 m = go m
  where go μ n
    | μ > n     = 0
    | otherwise = (c + μ)^n + go (μ+1) n
    c = m

Because otherwise, it can get out of control/memory pretty fast

2 Comments

Welcome to Stackoverflow. Good advice, but this answer would frankly have been better posted as a comment or edit to mine (once you have enough reputation, you can comment on other people's posts). It would be more worthwhile as a standalone answer if you elaborated on what this applicative-style mapping does. (BTW, you don't need the parens around (^ n) . (+ m).)
I understand, should I delete this post and comment on yours instead? Or add information about mapping and local-bound recursion? (I didn't have access to comment at the time of my post, I guess I should have just refrained)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.