【问题标题】:Scala: recursive implicit typeScala:递归隐式类型
【发布时间】:2015-11-26 06:16:34
【问题描述】:

我具有以下用于解析的特征,这些特征为对象的开头和结尾提供文件位置:

case class FilePosn(lineNum :Int, tabs: Int, spaces: Int, fileName: String)
{/*code omitted*/}

trait PosnEnds
{
  def startPosn: FilePosn
  def endPosn: FilePosn
  def multiLine: Boolean = startPosn.lineNum != endPosn.lineNum
  def OneLine: Boolean = startPosn.lineNum == endPosn.lineNum
  def indent: Int = startPosn.tabs
  def startLine: Int = startPosn.lineNum
  def endLine: Int = endPosn.lineNum
}

object FilePosnVoid extends FilePosn(0, 0, 0, "There is no File position")
{ override def posnString(indentSize: Int): String = "No File Posn: " }

在伴生对象中,我创建了一个隐式的,因此 PosnEnds 序列本身就是隐式 PosnEnds:

object PosnEnds
{
  implicit class ImpPosnEndsSeq[A <: PosnEnds](thisSeq: Seq[A]) extends PosnEnds
  {
    override def startPosn: FilePosn = thisSeq.fHead(FilePosnVoid, (h, t) => h.startPosn)
    override def endPosn: FilePosn = thisSeq.fLast(FilePosnVoid, _.endPosn)     
  }
}

是否可以递归地使用隐式,以便 Seq[Seq[A]] 和 Seq[Seq[Seq[A]]] 等将被隐式转换为 PosnEnds 特征? 在实践中我可能不需要很大的深度,但最好使用一个优雅的解决方案,隐式转换任意深度的 Seq。

目前我正在使用深度 2:

implicit class ImpPosnEndsSeqSeq[A <: PosnEnds](thisSeq: Seq[Seq[A]]) extends PosnEnds
{
  override def startPosn: FilePosn = thisSeq.fHead(FilePosnVoid, (h, t) => h.startPosn)
  override def endPosn: FilePosn = thisSeq.fLast(FilePosnVoid, _.endPosn)     
}

【问题讨论】:

  • 对于A 执行的两种情况,您是否期望trait PosnEnds 进行操作?

标签: scala scala-implicits


【解决方案1】:

是的。你可以用 typeclass 中介来做到这一点。

我允许自己对您的示例进行一些小改动,以使其更具重现性。在object PosnEnds里面我有

val void = new FilePosn(0, 0, 0, "There is no File position") {
  override def posnString(indentSize: Int): String = "No File Posn: "
}

def empty = new PosnEnds {
  def startPosn: FilePosn = void
  def endPosn: FilePosn = void
}

你首先需要的是一些简单的类型类,比如

trait MakePosnEnds[X] extends (X => PosnEnds)

现在您可以为归纳引入规范元素:

implicit object idMakePosnEnds extends MakePosnEnds[PosnEnds] {
  def apply(x: PosnEnds) = x
}

implicit def seqMakePosnEnds[X](implicit recur: MakePosnEnds[X]) = new MakePosnEnds[Seq[X]] {
  def apply(x: Seq[X]): PosnEnds = new PosnEnds {
    val thisSeq = x.map(recur)
    override def startPosn: FilePosn = thisSeq.headOption.fold(void)(_.startPosn)
    override def endPosn: FilePosn = thisSeq.lastOption.fold(void)(_.endPosn)
  }
}

最后你可以定义你的隐式转换

implicit def toPosnEnds[X](x: X)(implicit make: MakePosnEnds[X]): PosnEnds = make(x)

从这里开始

Seq(Seq(Seq(empty))).startLine

编译运行成功

与您的尝试的主要区别:我们不等待隐式转换到堆栈。隐式解析可以递归,但隐式转换不能。

所以我们使用了一些无值类型,即可以只使用隐式参数来实现的东西,这意味着可以由编译器构造。 然后才把这个逻辑投射到具体的价值上。

【讨论】:

  • 我似乎无法使用您的代码获得隐含功能,即使在使用文件中使用导入也是如此。
  • @RichOliver 很伤心。尝试将它们全部放在object Implicits 和import Implicits._ 中。另请注意,如果您的旧 implicit class ImpPosnEndsSeq 在目标源中仍然可见,则它可能与 def toPosnEnds 冲突
猜你喜欢
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2021-10-14
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多