简体   繁体   中英

F# Sum of products of an array with element position

Coming of a C# background and trying to learn F#.
I'm trying to iterate over an array of size 256, so the total sum of it be the product of the element position and the element, like this:

float sum = 0.0;
for (int i = 0; i < 256; i++) {
    sum += i * arr[i];
}

I made this but I don't know if this is the best way to do it in F#, probably not.

let mutable sum = 0
for i in 0 .. 255 do
    sum <- sum + i * arr.[i]
done

I don't know if it's possible to use Array.fold or Array.iteri to solve this in a better way.

您可以使用mapisum

let f s = s |> Seq.mapi (fun i j -> i * j) |> Seq.sum

One way of doing this with only one iteration through the array:

let f s = snd (Array.fold (fun (i, sum) x -> (i + 1, sum + x * float i)) (0, 0.0) s)

Although I prefer Lee's solution as being much easier to follow.

An alternative would be to write your own Array.foldi function and use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM