F#中的通用类型注释 [英] Generic type annotation in F#
问题描述
我遇到以下错误:
错误2值限制.已经推断出值
'gbmLikelihood'
具有通用类型val gbmLikelihood : (float -> '_a -> float [] -> float) when '_a :> seq<float>
,或者将'gbmLikelihood'
的参数设为显式,或者,如果您不希望它成为通用类型,则添加类型注释.
Error 2 Value restriction. The value
'gbmLikelihood'
has been inferred to have generic typeval gbmLikelihood : (float -> '_a -> float [] -> float) when '_a :> seq<float>
Either make the arguments to'gbmLikelihood'
explicit or, if you do not intend for it to be generic, add a type annotation.
这种类型正是我想要的.我必须做些什么才能使其正常工作,为什么它在没有干预的情况下也无法正常工作?
and this type is exactly what I want. What do I have to do to make it work, and why doesn't it just work without intervention?
错误来自此文件(简短,因此我将全部粘贴):
The error comes from this file (its short, so I paste the whole lot):
module Likelihood
open System
let likelihood getDrift getVol dt data parameters =
let m = getDrift data parameters
let s = getVol data parameters
let N = float (Seq.length data)
let sqrt_dt = Math.Sqrt dt
let constant = -0.5*Math.Log(2.0*Math.PI*dt)*N
let normalizedResidue observation = (observation - (m - 0.5*s*s)*dt)/(s*sqrt_dt)
let residueSquared observation =
let r = normalizedResidue observation in r*r
let logStdDev = Math.Log s
constant - logStdDev*N - 0.5* (data |> Seq.sumBy residueSquared)
let gbmLikelihood = likelihood (fun data p -> Array.get p 0) (fun datac p -> Array.get p 1)
推荐答案
当您声明具有通用类型的 value 时,可能会发生此错误.参见例如过去的SO问题.在您的情况下,该类型表明您正在尝试定义一个函数,但是编译器并不将其视为语法函数.如果执行某些效果,然后使用lambda语法返回函数,则会发生这种情况:
This error can happen when you declare a value that has a generic type. See for example this past SO question. In your case, the type suggests that you are trying to define a function, but the compiler does not see it as a syntactic function. This can happen if you perform some effects and then return function using the lambda syntax:
let wrong =
printfn "test"
(fun x -> x)
为避免此问题,您需要使用函数语法编写函数:
To avoid the problem, you need to write the function using the function syntax:
printfn "test"
let wrong x = x
编辑:在您的具体示例中,功能gbmLikelihood
是由于部分功能应用程序而创建的.要使其编译,您需要将其转换为显式函数:
In your concrete example, the function gbmLikelihood
is created as a result of a partial function application. To make it compile, you need to turn it into an explicit function:
let gbmLikelihood parameters =
likelihood (fun data p -> Array.get p 0) (fun datac p -> Array.get p 1) parameters
For more information why this is the case & how it works, see also this great article on value restriction in F#.
这篇关于F#中的通用类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!