值限制:已将类型"bar"推断为具有通用类型 [英] Value restriction: The type 'bar' has been inferred to have generic type
问题描述
在下面的代码段中,我看不到为什么必须按功能foo
的方式编写f
和g
以及为何按功能bar
的方式无法实现.
In the snippet below, I cannot see why I have to compose f
and g
the way function foo
does and why it does not work the way function bar
tries to do it.
let f a b = a,b
let g (a : 'a) (b : 'a) = a
let (>!) f1 f2 =
fun a b ->
let (x,y) = f1 a b
f2 x y
let foo = fun a b -> (f >! g) a b
let bar = f >! g
任何人都可以向我解释为什么bar
无法正常工作吗?鉴于foo
也具有通用类型,对我来说这没有意义.
Can anyone explain to me, why bar
is not working? Given that foo
also has generic type, it makes no sense to me.
推荐答案
foo
是一个函数,而bar
是一个值.是的,它是一个函数类型的值,但仍然是一个值.那里有一个细微的差别.
foo
is a function, while bar
is a value. Yes, it's a value of a function type, but still a value. There is a subtle difference there.
F#编译器可以看到" foo
是一个函数,因为它可以在let
之后立即看到fun ->
.
The F# compiler can "see" that foo
is a function, because it sees the fun ->
right after let
.
您的bar
是真实值-通过调用其他函数(运算符>!
)获得的结果. F#有一条规则(称为值限制")(每天)说,值(不同于函数)不能具有泛型类型,除非显式指定了泛型参数,从而有效地使其成为类型函数". (比这稍微复杂一点,请阅读下面的链接以获取完整图片)
Your bar
, on the other hand, is a true value - a result obtained by invoking a different function (the operator >!
). F# has a rule (known as "value restriction") saying (in everyday terms) that values (unlike functions) cannot have generic types, unless generic arguments are specified explicitly, thus effectively making it a "type function". (it's a bit more complicated than that, read the links below for the full picture)
这不是特定于F#的-ML的其他非纯变体也具有此功能. 此处是对此规则的讨论F#和此处是关于SML的讨论.
This is not specific to F#, though - other non-pure variants of ML have this as well. Here is a discussion of this rule for F#, and here's a discussion for SML.
这篇关于值限制:已将类型"bar"推断为具有通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!