How to sum a number in a list

171 Views Asked by At

My question is :

I have a list and a number and I want to sum the number to the list so I can do this

Adding ls n = [x+n| x<-ls] 

and it works.

My question is I want to add n+1, n+2, n+3 depending of the length of the list.

If I do

let b = 0
Adding´ ls n = [x+adder n b| x<-ls] where adder n b= n+b,b++

it doesn't work because the b doesn't advance, so if I have Adding´ [1,3,4] 3 = [4,7,9] .

2

There are 2 best solutions below

1
Redu On

You may use Data.List.mapAccumL (mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)) to achieve this task.

The first parameter is a function which takes two parameters a (accumulator) and n (the list item) and returns a tuple. In our case we increment a (the accumulator) by 1 and map the current element n by adding the accumulator. The result is a tuple in which the first item is the final state of the accumulator and the second is the final state of the list. We extract the second item by snd.

Prelude> snd $ Data.List.mapAccumL (\a n -> (a+1,n+a)) 3 [1,3,4]
[4,7,9]
0
chepner On

Approach the problem recursively. Add a number to the first element of the list, then recurse on the tail of the list with the next larger number. Repeat until you are out of numbers. Instead of incrementing b, you start a new function call in which b has a larger value.

adding [] _ = []
adding (x:xs) b = x + b : adding xs (b+1)

As an example, consider

adding [7, 10, 7, 5] 0 == 7 + 0 : adding [10, 7, 5] 1
                       == 7     : (10 + 1 : adding [7, 5] 2)
                       == 7     : 11      : (7 + 2 : adding [5] 3)
                       == 7     : 11      : 9      : (5 + 3 : adding [] 4)
                       == 7     : 11      : 9      : 8      : []
                       == [7, 11, 9, 8]

You can replace 0 with any starting value n in the initial call; the recursive call always increments it.