F # the sum of all the remaining elements in the list

Lets say that I have a function definition:

let sum (numbers: int list) = // code here 

What are the possible ways to calculate the sum of all the other elements in the list of numbers? Therefore, if the result of [3;5;3;7] is [(3, 15); (5, 13); (3, 15); (7, 11)] [(3, 15); (5, 13); (3, 15); (7, 11)] [(3, 15); (5, 13); (3, 15); (7, 11)] .

Im really interested in any solutions, especially those that use a functional approach.

thanks

+7
functional-programming f #
source share
2 answers

You can do this rather naively by adding up a list and then returning a tuple (x, sum - x) for each x element in the list:

 let sum (numbers: int list) : (int * int) list = let s = List.sum numbers numbers |> List.map(fun x -> (x, sx)) let nums = [3;5;3;7] printfn "%A" (sum nums) // [(3, 15); (5, 13); (3, 15); (7, 11)] 
+12
source share

You can apply mapFold and use this state to find out if the first occurrence has been detected.

 let excludeAndSum (numbers: int list) i = numbers |> Seq.mapFold (fun ci' -> (i', c||i<>i'), c||i=i') false |> fst |> Seq.filter snd |> Seq.sumBy fst let sum numbers = List.map (fun i -> i , excludeAndSum numbers i) numbers 
+4
source share

All Articles