无限类型(又名递归类型)在 F# 中是不可能的吗? [英] Are Infinite Types (aka Recursive Types) not possible in F#?
问题描述
我在 twitter 上与 Sadek Drobi 聊天时被提到 F# 似乎不支持无限类型.事实证明,在 C# 中,您可以按照以下方式做一些事情:
delegate RecDelegateRecDelegate (T x);
但是,经过我们双方的一些实验后,我们确定 F# 中的相同似乎不可能隐式和显式.
显式:
type 'a specialF = 'a->specialF<'a>
<块引用>
错误 FS0191:此类型定义涉及立即循环引用通过缩写,struct 字段或继承关系.
隐式:
let rec specialF (x: 'a) = specialF
<块引用>
类型不匹配.期待一个 'b 但是给定一个'a -> 'b.结果类型统一''b'时将是无限的和 ''a -> 'b'.
当然,这些都是有意为之的简单示例.
我想知道我是不是弄错了.也许我错过了某种必要的注释?
你也可以这样做
type 'a RecType = RecType of ('a -> 'a RecType)
创建一个命名类型,通过它执行递归.现在这有效:
let rec specialF = RecType (fun _ -> specialF)
I was chatting with Sadek Drobi on twitter when be brought up that F# didn't seem to support Infinite Types. It turns out that in C# you can do something along these lines:
delegate RecDelegate<T> RecDelegate<T>(T x);
However, after some experimentation on both our parts, we determined that the same in F# seems impossible both implicit and explicitly.
Explicit:
type 'a specialF = 'a->specialF<'a>
error FS0191: This type definition involves an immediate cyclic reference through an abbreviation, struct field or inheritance relation.
Implicit:
let rec specialF (x: 'a) = specialF
Type mismatch. Expecting a 'b but given a 'a -> 'b. The resulting type would be infinite when unifying ''b' and ''a -> 'b'.
Of course, these are intentionally simple samples.
I was wondering if I am somehow mistaken. Perhaps I missed some type of necessary annotation?
You can also do something like
type 'a RecType = RecType of ('a -> 'a RecType)
to create a named type through which to perform the recursion. Now this works:
let rec specialF = RecType (fun _ -> specialF)
这篇关于无限类型(又名递归类型)在 F# 中是不可能的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!