开发者

Cycling pipelining

I have a matrix: Array2D and a function

let DivideAndSubstract value index (matrix: float[,]) = 
    //something that returns a matrix

so I need to apply this function n times to my matrix like that:

matrix  
|> DivideAndSubstract matrix.[0,0] 0  
|> DivideAndSubstract matrix.[1,1] 1  
|> DivideAndSubstract matrix.[2,2] 2  
....  
|> DivideAndSubstract matrix.[n,n] n 

where n = Array2D.length1 matrix - 1

How can I implement this pip开发者_StackOverflowelining?


From the top of my head:

{0..n} |> Seq.fold (fun M k -> DivideAndSubtract matrix.[k,k] k M) matrix

Edit: a few more words won't hurt the answer:

Using a fold is a typical pattern of 'apply F to x and apply F to the result and apply F to that result ... until I don't need to apply F again'. The imperative version of the line above would be

let mutable M = matrix
for k in 0..n do
    M <- DivideAndSubtract matrix.[k,k] k M
M

Inside the fold, M denotes the intermediate result at each step. It may take a while to grasp how folds work, but once you do, they're pretty powerful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜