如何使用类型别名来描述此递归语法:
type FieldValue = Seq[String] :+: String :+: Int :+: Long :+: CNil
type FieldLeaf = FieldValue :+: SubField :+: CNil
type SubField = Seq[Field]
type Field = (String, FieldLeaf)
就目前而言,Scala编译器(2.12.1)给了我:
Error:(14, 25) illegal cyclic reference involving type FieldLeaf
type Field = (String, FieldLeaf)
PS的上下文是使用fastparse解析递归语法。
编辑(回复@ OlivierBlanvillain'以下答案)
这个答案真的很美,而且正是我想要的,我会记住它的未来。
然而,由于其他原因,在这种特殊情况下,我不得不采用这些定义:
case class Field(name: String, leaf: FieldLeaf)
sealed trait FieldLeaf
sealed trait FieldValue extends FieldLeaf
case class StringsFieldValue(value: Seq[String]) extends FieldValue
case class StringFieldValue(value: String) extends FieldValue
case class IntFieldValue(value: Int) extends FieldValue
case class LongFieldValue(value: Long) extends FieldValue
case class SubField(value: Seq[Field]) extends FieldLeaf
答案 0 :(得分:3)
使用修正点类型。例如:
case class Fix[F[_]](out: F[Fix[F]])
让你写:
type FieldValue = Seq[String] :+: String :+: Int :+: Long :+: CNil
type FieldLeaf[F] = FieldValue :+: SubField[F] :+: CNil
type SubField[F] = Seq[F]
type Field0[F] = (String, FieldLeaf[F])
type Field = Fix[Field0]