How to refactor code to make it functional style?

后端 未结 3 1337
星月不相逢
星月不相逢 2021-01-14 15:01

Playing with F#, I\'m trying to think of code in a more functional way. A large part of my work happens to be numerical in nature so I\'m thinking whether this re-education

3条回答
  •  一个人的身影
    2021-01-14 15:24

    I think this is a very good question. My impression is that the trouble you will run into when writing functional numerical code (think Matlab vs Mathematica) is not with the syntax but rather performance. But at the same time it is also very easy to parallelize the code.

    I would write your code this way:

    let arr1' = [|for i in 0..1000 -> Array.init i (fun i -> Exponential.Sample(0.1)) |> Statistics.Mean |]

    Notice that a) there is no mutable assignment, b) no indexing and c) I don't initialize a 0 based array and fill it but instead initialize the array with the function.

    I would also investigate if it's possible to generate the samples directly with Exponential.Sample, instead of calling it a 1,000 times.

    Edit

    Like this: Exponential.Samples(0.1) |> Seq.take 1000

    And based on @ChristophRüegg's comment below:

    let expoMean (x:float []) =
        Exponential.Samples(x,0.1)
        x |> Statistics.Mean
    
    Array.init 1000 (fun _ -> Array.replicate 1000 0. |> expoMean)
    

    I haven't benchmarked this.

提交回复
热议问题