无法在Shapeless FoldRight之后将HList转换为元组

问题描述 投票:0回答:1

我正在尝试使用Scala在案例类中创建CSV文件的解析器,并正在尝试使用Shapeless使它通用。

我希望我的解析器允许用户指定提取函数extract: CsvRow => String,而不是具有特定字段类型的1对1对应关系和类型类,因为我正在解析的文件格式不同,并且解析操作会适用于一个文件不适用于另一文件。我想,如果可以通过首先进行“哑”解析然后应用转换函数来避免此步骤,但最终,我只是将注意力转移到需要解决此问题的地方。

此后,我想将生成的HList转换为元组,并执行mapN来创建case类的新实例

我尝试了几种策略,但是我总是遇到一些不起作用的问题。我发现以下内容对我很有帮助this specific answer

此刻我不断得到

could not find implicit value for parameter tupler

当我尝试将结果HList转换为元组时。我注意到,我得到的HList终止于HNil.type而不是我期望的HNil终止

UPDATE:我在Scastie上添加了更完整的代码,其中包含更多注释和数据。

版本:

  • SBT 1.2.8
  • Scala 2.13.0
  • 无形状2.3.3
import CsvDefinitions._
import CsvTypeParser._
import CsvConverter._
import cats.data._
import cats.implicits._
import scala.util.Try
import shapeless._
import shapeless.ops.hlist.RightFolder
import shapeless.syntax.std.tuple._

object CsvDefinitions {
  type CsvRow = List[String]
  type CsvValidated[A] = ValidatedNec[Throwable, A]
  // A parser is a function that given a row returns a validted result
  type CsvRowParser[A] = Kleisli[CsvValidated, CsvRow, A]
}

trait CsvTypeParser[A] {
  def parseCell(cell: String): CsvValidated[A]
}

object CsvTypeParser {
  def parse[A](extract: CsvRow => String)(implicit parser: CsvTypeParser[A]): CsvRowParser[A] =
    Kleisli { row =>
      val extracted = Try(extract(row)).toEither.toValidatedNec
      val parsed = parser.parseCell _
      (extracted) andThen parsed
    }
  def apply[A](f: String => A): CsvTypeParser[A] = new CsvTypeParser[A] {
    def parseCell(cell: String): CsvValidated[A] = Try(f(cell)).toEither.toValidatedNec
  }
  implicit val stringParser: CsvTypeParser[String] = CsvTypeParser[String] {
    _.trim
  }
  implicit val intParser: CsvTypeParser[Int] = CsvTypeParser[Int] {
    _.trim.toInt
  }
  implicit val doubleParser: CsvTypeParser[Double] = CsvTypeParser[Double] {
    _.trim.toDouble
  }
}

object CsvConverter {
  // The following has been adapted from https://stackoverflow.com/a/25316124:
  private object ApplyRow extends Poly2 {
    // The "trick" here is to pass the row as the initial value of the fold and carry it along
    // during the computation. Inside the computation we apply a parser using row as parameter and
    // then we append it to the accumulator.
    implicit def aDefault[T, V <: HList] = at[CsvRowParser[T], (CsvRow, V)] {
      case (rowParser, (row, accumulator)) => (row, rowParser(row) :: accumulator)
    }
  }

  def convertRowGeneric[
    HP <: HList,    // HList Parsers
    HV <: HList](   // HList Validated
      input: HP,
      row: CsvRow)(
      implicit
        // I tried to use the RightFolder.Aux reading https://stackoverflow.com/a/54417915
        folder: RightFolder.Aux[
          HP,                   // Input type
          (CsvRow, HNil.type),  // Initial value of accumulator
          ApplyRow.type,        // Polymorphic function
          (CsvRow, HV)          // Result type
        ]
      ): HV = {
    input.foldRight((row, HNil))(ApplyRow)._2
  }
}

// Case class containing the final result of the conversion
case class FinalData(id: Int, name: String, score: Double)

object Main extends App {

  // Definition of parsers and how they obtain the value to parse
  val parsers =
    parse[Int   ](r => r(0)) ::          // Extract field 0 and convert it to Int
    parse[String](r => r(1)+" "+r(2)) :: // Get field 1 and 2 together
    parse[Double](r => r(3).trim) ::     // Trim field 3 before converting to double
    HNil

  // One line in the CSV file
  val row = List("123", "Matt", "Smith", "45.67")

  val validated = convertRowGeneric(parsers, row)
  println(validated)  

  // Could not find implicit value for parameter tupler
  // The "validated" HList terminates with HNil.type
  val finalData = validated
    .tupled
    .mapN(FinalData)
  println(finalData)
}
scala shapeless scala-cats
1个回答
0
投票

修复convertRowGeneric(用HNil.type替换类型HNil,并用名称HNil替换值HNil: HNil

def convertRowGeneric[
  HP <: HList,    // HList Parsers
  HV <: HList](   // HList Validated
                  input: HP,
                  row: CsvRow)(
                implicit
                folder: RightFolder.Aux[
                  HP,                   // Input type
                  (CsvRow, HNil),  // Initial value of accumulator
                  ApplyRow.type,        // Polymorphic function
                  (CsvRow, HV)          // Result type
                ]
              ): HV = {
  input.foldRight((row, HNil: HNil))(ApplyRow)._2
}
© www.soinside.com 2019 - 2024. All rights reserved.