gpt4 book ai didi

recursion - 具有递归的 F# 求和类型?

转载 作者:行者123 更新时间:2023-12-05 09:06:31 25 4
gpt4 key购买 nike

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

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 中(例如),我可以定义一个内联求和类型,这样求和类型中的一种类型就是被定义的类型本身:

case class Type1()

case class Type2(x: Type1 | Type2)

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

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

最佳答案

您可以使用 type ... and 语法来做到这一点,它可以让您定义一组相互递归的类型定义:

type Type1() = 
class end

type Type1OrType2 = T1 of Type1 | T2 of Type2

and Type2(x: Type1OrType2) =
class end

关于recursion - 具有递归的 F# 求和类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65910858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com