Continuing my F# learning today by attempting to recreate a simple bisection method using recursion, here I am using the MathNet library to inherit from the Beta distribution.
I receive errors on the function ‘search’ (binary search method) saying the value is not a function and cannot be applied.
//Beta class inheriting from MathNet Beta distribution
//Extends the class by implementing an InverseCDF function
type newBeta(alpha:double, beta:double) =
inherit MathNet.Numerics.Distributions.Beta(alpha, beta)
member this.InverseCDF(p: float) =
let rec search (min: float, max: float, acc: uint32) =
let x = (min + max) / 2.0
let error = 0.001
let maxiters : uint32 = 1000u
let cdf = this.CumulativeDistribution(x)
match cdf, (Math.Abs(cdf - p) < error || acc > maxiters) with //while statement
| _ , true -> cdf //auto match cdf and if while statement evaluates true then break and return cdf result
| p , _ -> cdf //if exactly matches p then break and return cdf result
| p , false when p > cdf -> search (min) (x) (acc + 1) //if p > cdf then set max = x and increment then call func with new params
| p , false when p < cdf -> search (x) (max) (acc + 1) //if p < cdf then set min = x and increment then call func with new params
search (0.0) (1.0) (0) //Call the bisection method with initial parameters
Can anyone help? Also obviously any input on how to make this more ‘functional’ would be cool. Havn’t been able to run this yet to test due to the error though. My first 2 match patterns look suspect given I’m trying to return the current value of cdf.
As @John said, your fundamental error is that you declared the function in the tuple form but used it in the curried form.
I notice that you pattern-matched
cdfwithp. The new valuepwill shadow parameterpofthis.InverseCDF; therefore, that parameter isn’t available for comparison anymore. You actually comparedcdfwithcdfitself and twowhenguards are alwaysfalse, which you do not want at all.A few corrections:
cdffrom pattern matching since you only want to compare its value withp, not match with specific literals.whenguards up. The last pattern shouldn’t be awhenguard; the compiler will complain about incomplete pattern matching in that case.ufor any arithmetic operation onacc(which is of typeunint32).The new
searchfunction: