Ric*_*odd 1 f# function pattern-matching
通过尝试使用递归重新创建一个简单的二分法来继续我的F#学习,这里我使用MathNet库继承Beta分布.
我收到函数'search'(二进制搜索方法)的错误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
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?显然,任何关于如何使这个更"功能"的输入都会很酷.但由于错误,尚未能运行此测试.鉴于我正在尝试返回当前值,我的前2个匹配模式看起来很可疑cdf
.
正如@John所说,你的根本错误是你以元组形式声明了函数,但是以curry形式使用它.
我注意到你的图案匹配cdf
带p
.新值p
将跟随参数p
的this.InverseCDF
; 因此,该参数不再可用于比较.你实际上cdf
与cdf
自己相比,when
总是有两个守卫false
,你完全不想要.
一些更正:
cdf
从模式匹配中删除,因为您只想比较其值p
,而不是与特定文字匹配.when
警卫.最后的模式不应该是一个when
后卫; 在这种情况下,编译器会抱怨不完整的模式匹配.u
对任何算术运算使用后缀acc
(属于类型unint32
).新search
功能:
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 abs(cdf - p) < error || acc > maxiters with // while statement
| false when p > cdf -> search min x (acc + 1u) // if p > cdf then set max = x and increment then call func with new params
| false when p < cdf -> search x max (acc + 1u) // if p < cdf then set min = x and increment then call func with new params
| _ -> cdf // if exactly matches p or returns true then break and return cdf result
search 0.0 1.0 0u // call the bisection method with initial parameters
Run Code Online (Sandbox Code Playgroud)