Still in the process of turning my code more and more functional in style as well as in look.
Here I have a function which I try to keep as generic as I can, passing a filter function and a calculation function as parameters.
let calcError filter (fcalc:'a -> float) (arr:'a array) =
arr |> Array.filter filter
|> Array.map fcalc
|> Array.average
The signature is:
val calcError : filter:('a -> bool) -> fcalc:('a -> float) -> arr:'a array -> float
I believe this is quite standard, using calcError with partial applications.
However Array.average will raise exceptions is array is of size 0 or if null (which will not happen in my case).
Not a big fan of Exceptions in F#, I would prefer using either a (float output) or a Result.
I would then think of writing the code this way but I am not sure it is a proper way to do within a functional mindset (that I am trying to acquire). Any other solution, which I could probably be able to adapt for other similar issues, is of course welcome.
Thanks all
Solution I have in mind:
let calcError2 filter (fcalc:'a -> float) (arr:'a array) =
let subarr = arr |> Array.filter filter
match subarr.Length with
| 0 -> Result.Error "array length 0"
| _ -> subarr |> Array.map fcalc
|> Array.average
|> Result.Ok