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
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)]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With