Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return sum of sublist in a list

Tags:

f#

I've been trying to figure this out for the last few hours with no success what so ever.

Let's say I have a list of lists of int

let list = [[1;3;4;4];[1;3]]

I have to create a function that will sum the sublists and return one list as below:

[12;4]

I've been told that I should use List.fold.

I've tried the following:

let list = [2;3;5]
let sumList list = List.fold (fun acc elem -> acc + elem) 0 list
sumList list

this is returning only an int and works only for an int list and not for a list of list. What are the next steps from here.

like image 516
Julius Knafl Avatar asked Sep 29 '16 12:09

Julius Knafl


People also ask

How do you sum a sublist?

Given a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j). For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return sum([2, 3]), which is 5. You can assume that you can do some pre-processing.

How do you find the sum of a nested list?

We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension. Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.

How do you sum parts of a list?

Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.


1 Answers

Try:

list 
|> List.map List.sum

So you map the List.sum for each element in the list.

Or with fold:

list 
|> List.map (List.fold (+) 0)

(List.fold (+) 0) is the same as the sum function. It starts with zero and adds in each iteration the value to the accumulator.

list 
|> List.fold (fun acc v -> 
    acc @ [(List.fold (+) 0) v]) []

As you see, you can also replace the map with a fold.

list 
|> List.foldBack (fun v acc -> 
    (List.fold (+) 0 v) :: acc) 
    <| []

With List.foldBack it looks a little bit better in my opinion than with fold. But I prefer the first solution.

like image 92
Peter Siebke Avatar answered Nov 15 '22 09:11

Peter Siebke