用类型别名描述递归语法 [英] Describe recursive grammar with type aliases
本文介绍了用类型别名描述递归语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何用类型别名描述此递归语法:
How can I describe this recursive grammar with type aliases:
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)给我:
As it stands, the Scala compiler (2.12.1) gives me:
Error:(14, 25) illegal cyclic reference involving type FieldLeaf
type Field = (String, FieldLeaf)
PS的上下文是使用 fastparse 解析递归语法.
PS the context of this is parsing a recursive grammar with fastparse.
编辑(以回应下面@OlivierBlanvillain的回答)
这个答案确实是一件很美的事情,而且正是我一直在寻找的东西,我会为将来记住它.
That answer was really a thing of beauty and exactly what I was looking for, I'll remember it for the future.
但是,由于其他原因,在这种情况下,我不得不采用以下定义:
However, for other reasons, in this particular case I had to go with these definitions instead:
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
另请参阅: 从递归类型语法实例化
See also: Instantiate types from recursive type grammar
推荐答案
使用定位点类型.例如:
Use a fix point type. For example:
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]
这篇关于用类型别名描述递归语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文