1

I'm writing a function that takes an int list and returns a sum using scanl

Below code works.

Input: [1,2,3]

sum_calc list = scanl (+) 0 [1..10]

Output: [0,1,3,6,10,15,21,28,36,45,55]

I want to edit it so that the output only goes up to the last element of the inputted list. I've tried using 0 [1..length list] but haskell spits this out at me.

4
  • Sorry, but what output do you want to get when run sum_calc [1, 2, 3]? Just 6? Commented Aug 14, 2020 at 11:59
  • 1
    @SergeyKuz1001 I think OP wants sum_calc [1, 2, 3] == [0, 1, 3] (i.e. the cumulative sums of the list). Commented Aug 14, 2020 at 12:02
  • @SergeyKuz1001 so it should return [0, 1, 3, 6] .. so first is 0, and second is the first inputted value, third is the first and second inputted value added together, fourth would be that value added to the fourth element of the input. If that makes sense? Commented Aug 14, 2020 at 12:03
  • 1
    @pythonstudent98 I’d rather not write your code for you, but here’s a hint: your code is almost there, but when you call sum_calc as it is currently written, it returns the cumulative sums of the list [1..10] rather than those of the input list list. How can you alter your code to use the input list? Commented Aug 14, 2020 at 12:04

1 Answer 1

1

You can write this:

sum_calc = scanl (+) 0

So sum_calc [1, 2, 3] return [0, 1, 3, 6].

You can also write

sum_calc list = scanl (+) 0 list

if you are confused by disappearance of list.

Sign up to request clarification or add additional context in comments.

3 Comments

@pythonstudent98 What happens when you try it?
@pythonstudent98 That’s really weird — the presence or absence of list should have no effect whatsoever on how sum_calc works. What happens when you don’t include list?
@bradrn Probably the monomorphism restriction strikes.

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.