F#中的通用类型注释

编程入门 行业动态 更新时间:2024-10-26 00:28:25
本文介绍了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 type val 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

有关更多信息,请参见为什么&运作方式,另请参阅出色的有关F#中的值限制的文章.

For more information why this is the case & how it works, see also this great article on value restriction in F#.

更多推荐

F#中的通用类型注释

本文发布于:2023-07-30 15:20:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!