类型的功能(单位->单位)可以在F#中具有静态解析的类型参数吗? [英] Can a function of type (unit -> unit) have statically resolved type parameters in F#?
问题描述
为什么不允许这样做?
type Foo() =
static member Bar() = ()
let inline bar<^a>() = //ERROR: unexpected infix operator in pattern
(^a : (static member Bar : unit -> unit)())
//Hypothetical usage: let _ = bar<Foo>()
...但这很好吗?
type Foo() =
static member Bar() = new Foo()
let inline bar() : ^a =
(^a : (static member Bar : unit -> ^a)())
let x : Foo = bar()
是否需要具有静态解析类型参数的函数来返回解析类型的实例?
Are functions with statically resolved type parameters required to return an instance of the resolved type?
推荐答案
正如您所注意到的,F#将字符<^
的序列视为中缀运算符,因此您需要用空格分隔它们.关于何时需要显式指定约束的问题,我认为规则是,当您显式提供函数类型参数时,还需要指定任何必要的约束.否则,如果F#可以推断类型参数和约束,则无需指定它们.
As you noticed, F# treats the sequence of characters <^
as an infix operator, so you need to separate them with a space. As to the question of when you need to explicitly specify constraints, I believe that the rule is that when you explicitly give a function type parameters then you also need to specify any necessary constraints. Otherwise, if F# can infer the type parameters and constraints, you don't need to specify them.
因此,您提出的问题中的这个示例很好用:
So this example from your question works fine:
let inline bar() :^a =
(^a : (static member Bar : unit -> ^a)())
是这样的:
let inline bar(x : ^a) =
(^a : (static member Bar : unit -> unit)())
因为有一个泛型类型参数,但是您尚未将其显式放置在函数上,因此F#可以推断出所需的约束.
because there's a generic type parameter, but you haven't explicitly placed it on the function, and F# can infer the needed constraint.
另一方面,如果您尝试修改其他示例以省略显式的泛型参数:
On the other hand, if you try to modify your other example to omit the explicit generic parameter:
let inline bar() =
(^a : (static member Bar : unit -> unit)())
您将看到F#不允许这样做,因为它无法解决如何为bar()
的任何给定调用实例化^a
的方法.因此,您需要显式提供type参数,并且一旦完成,还必须显式提供约束.
You'll see that F# won't allow this because there's no way for it to figure out how to instantiate ^a
for any given call of bar()
. Thus, you need to provide the type parameter explicitly, and once you do, you also have to explicitly provide the constraint.
这篇关于类型的功能(单位->单位)可以在F#中具有静态解析的类型参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!