F#中不可能使用无限类型(又称为递归类型)吗? [英] Are Infinite Types (aka Recursive Types) not possible in F#?

查看:61
本文介绍了F#中不可能使用无限类型(又称为递归类型)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Twitter上与 Sadek Drobi 聊天时,被告知F#似乎不支持无限类型.事实证明,在C#中,您可以按照以下方式进行操作:

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);

但是,在我们对这两个部分进行了一些实验之后,我们确定无论在隐式还是显式中,F#中的相同似乎都是不可能的.

However, after some experimentation on both our parts, we determined that the same in F# seems impossible both implicit and explicitly.

明确:

type 'a specialF = 'a->specialF<'a>

错误FS0191:此类型定义 涉及立即循环参考 通过缩写struct字段 或继承关系.

error FS0191: This type definition involves an immediate cyclic reference through an abbreviation, struct field or inheritance relation.

隐含性:

let rec specialF (x: 'a) = specialF

类型不匹配.期待'b但是 给定一个'a->'b.结果类型 统一"b"时将是无限的 和"a->'b'.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆