Recursion F#带递归的和类型?
我试图用一个构造函数定义一个类型,该构造函数接收自身或另一个类型的sum类型。但是,因为我必须单独定义sum类型,sum类型或sum类型中使用的一个类型在构造函数处未定义Recursion F#带递归的和类型?,recursion,f#,algebraic-data-types,Recursion,F#,Algebraic Data Types,我试图用一个构造函数定义一个类型,该构造函数接收自身或另一个类型的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) = // Sam
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#中对这种类型的求和类型进行“内联”定义,从而利用递归?您可以使用
类型。。。和
语法,用于定义一组相互递归的类型定义:
Type1()类型=
班尾
类型1或类型2=类型1的T1 |类型2的T2
和类型2(x:Type1或Type2)=
班尾
另一种方法是使模块递归:
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