Generic type annotation in F#

后端 未结 2 1267
面向向阳花
面向向阳花 2021-01-21 01:46

I got the following error:

Error 2 Value restriction. The value \'gbmLikelihood\' has been inferred to have generic type val gbm

相关标签:
2条回答
  • 2021-01-21 02:24

    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
    

    EDIT: 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#.

    0 讨论(0)
  • 2021-01-21 02:25

    Instead of making the parameters of gbmLikelihood explicit you might also just add a generic type annotation to the function:

    let gbmLikelihood<'a> = 
        likelihood (fun data p -> Array.get p 0) (fun datac p -> Array.get p 1)
    
    0 讨论(0)
提交回复
热议问题