带递归的 F# sum 类型?

问题描述

我正在尝试使用构造函数定义类型,该构造函数接收自身或其他类型的总和类型。但是因为我必须单独定义 sum 类型,所以 sum 类型或 sum 类型中使用的类型之一在构造函数点是未定义的。

module BasicFunctions =

type Type1() = 
    class end

type Type1OrType2 = T1 of Type1 | T2 of Type2 // Type2 not yet defined

type Type2(x: Type1OrType2) = // Same thing for Type1OrType2 if Type1OrType2 is placed below Type2
    class end

在 Scala 中(例如),我可以内联定义 sum 类型,这样 sum 类型中的类型之一就是被定义的类型本身:

case class Type1()

case class Type2(x: Type1 | Type2)

@main def Main() =
  val t1 = Type1()
  val t2 = Type2(t1)
  val t3 = Type2(t2)

有没有办法在 F# 中对这种和类型进行“内联”定义,从而利用递归?

解决方法

您可以使用 def do_thing(path): with open(path) as fh: # do things with fh print(f"I can access fh: {not fh.closed}") print(f"And now we're done: {fh.closed}") do_thing('somefile.txt') I can access fh: True And now we're done: True 语法来做到这一点,它允许您定义一组相互递归的类型定义:

type ... and
,

另一种方法是使模块递归:

module rec BasicFunctions =

    type Type1() = 
        class end

    type Type1OrType2 = T1 of Type1 | T2 of Type2 // Type2 not yet defined

    type Type2(x: Type1OrType2) = // Same thing for Type1OrType2 if Type1OrType2 is placed below Type2
        class end

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...