Describe recursive grammar with type aliases

*爱你&永不变心* 提交于 2019-12-24 02:37:07

问题


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)

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 the context of this is parsing a recursive grammar with fastparse.


Edit (in response to @OlivierBlanvillain's answer below)

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


回答1:


Use a fix point type. For example:

case class Fix[F[_]](out: F[Fix[F]])

Lets you write:

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]


来源:https://stackoverflow.com/questions/42548402/describe-recursive-grammar-with-type-aliases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!