How To Apply a Function to an Array of float Arrays?

前端 未结 2 1765
执念已碎
执念已碎 2021-01-15 06:50

Let\'s suppose I have n arrays, where n is a variable (some number greater than 2, usually less than 10).

Each array has k elements.

I also have an array of

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 07:28

    Here's one solution:

    let combine weights arrs =
      Array.map2 (fun w -> Array.map ((*) w)) weights arrs 
      |> Array.reduce (Array.map2 (+))
    

    EDIT

    Here's some (much needed) explanation of how this works. Logically, we want to do the following:

    1. Apply each weight to its corresponding row.
    2. Add together the weight-adjusted rows.

    The two lines above do just that.

    1. We use the Array.map2 function to combine corresponding weights and rows; the way that we combine them is to multiply each element in the row by the weight, which is accomplished via the inner Array.map.
    2. Now we have an array of weighted rows and need to add them together. We can do this one step at a time by keeping a running sum, adding each array in turn. The way we sum two arrays pointwise is to use Array.map2 again, using (+) as the function for combining the elements from each. We wrap this in an Array.reduce to apply this addition function to each row in turn, starting with the first row.

    Hopefully this is a reasonably elegant approach to the problem, though the point-free style admittedly makes it a bit tricky to follow. However, note that it's not especially performant; doing in-place updates rather than creating new arrays with each application of map, map2, and reduce would be more efficient. Unfortunately, the standard library doesn't contain nice analogues of these operations which work in-place. It would be relatively easy to create such analogues, though, and they could be used in almost exactly the same way as I've done here.

提交回复
热议问题