Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# sum of all other elements in list

Lets say i have a function definition like this:

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

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

Im actually interested in any solutions, especially those which use functional approach.

Thanks

like image 276
Diverclaim Avatar asked Jun 15 '17 12:06

Diverclaim


2 Answers

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

let sum (numbers: int list) : (int * int) list = 
    let s = List.sum numbers
    numbers |> List.map(fun x -> (x, s-x))

let nums = [3;5;3;7]
printfn "%A" (sum nums) // [(3, 15); (5, 13); (3, 15); (7, 11)]
like image 115
goric Avatar answered Sep 28 '22 06:09

goric


You could apply mapFold and use the state to see if the first occurrence has already been found.

let excludeAndSum (numbers: int list) i = 
    numbers 
    |> Seq.mapFold (fun c i' -> (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
like image 33
Funk Avatar answered Sep 28 '22 06:09

Funk