57

我正在使用 Scala Combinators 制作解析器。太棒了。我最终得到的是一长串纠缠的案例类,例如:ClassDecl(Complex,List(VarDecl(Real,float), VarDecl(Imag,float))),只是长 100 倍。我想知道是否有一种以树状方式打印此类案例类的好方法,以便更容易阅读..?(或其他形式的Pretty Print

ClassDecl
  name = Complex
  fields =
  - VarDecl
      name = Real
      type = float
  - VarDecl
      name = Imag
      type = float

^ 我想以这样的方式结束

编辑:奖金问题

还有一种方法可以显示参数的名称..?喜欢:ClassDecl(name=Complex, fields=List( ... )

4

11 回答 11

38

查看一个名为sext的小型扩展库。它完全出于这样的目的导出这两个函数

以下是它如何用于您的示例:

object Demo extends App {

  import sext._

  case class ClassDecl( kind : Kind, list : List[ VarDecl ] )
  sealed trait Kind
  case object Complex extends Kind
  case class VarDecl( a : Int, b : String )


  val data = ClassDecl(Complex,List(VarDecl(1, "abcd"), VarDecl(2, "efgh")))
  println("treeString output:\n")
  println(data.treeString)
  println()
  println("valueTreeString output:\n")
  println(data.valueTreeString)

}

以下是该程序的输出:

treeString output:

ClassDecl:
- Complex
- List:
| - VarDecl:
| | - 1
| | - abcd
| - VarDecl:
| | - 2
| | - efgh

valueTreeString output:

- kind:
- list:
| - - a:
| | | 1
| | - b:
| | | abcd
| - - a:
| | | 2
| | - b:
| | | efgh
于 2013-03-30T13:16:46.933 回答
16

开始Scala 2.13case classes (它们是 的实现Product)现在提供了一个productElementNames方法,该方法返回其字段名称的迭代器。

结合Product::productIterator提供案例类的值,我们有一种简单的方法来漂亮地打印案例类而无需反射

def pprint(obj: Any, depth: Int = 0, paramName: Option[String] = None): Unit = {

  val indent = "  " * depth
  val prettyName = paramName.fold("")(x => s"$x: ")
  val ptype = obj match { case _: Iterable[Any] => "" case obj: Product => obj.productPrefix case _ => obj.toString }

  println(s"$indent$prettyName$ptype")

  obj match {
    case seq: Iterable[Any] =>
      seq.foreach(pprint(_, depth + 1))
    case obj: Product =>
      (obj.productIterator zip obj.productElementNames)
        .foreach { case (subObj, paramName) => pprint(subObj, depth + 1, Some(paramName)) }
    case _ =>
  }
}

对于您的具体情况:

// sealed trait Kind
// case object Complex extends Kind
// case class VarDecl(a: Int, b: String)
// case class ClassDecl(kind: Kind, decls: List[VarDecl])

val data = ClassDecl(Complex, List(VarDecl(1, "abcd"), VarDecl(2, "efgh")))

pprint(data)

产生:

ClassDecl
  kind: Complex
  decls: 
    VarDecl
      a: 1
      b: abcd
    VarDecl
      a: 2
      b: efgh
于 2019-03-06T21:00:20.207 回答
13

使用 com.lihaoyi.pprint 库。

libraryDependencies += "com.lihaoyi" %% "pprint" % "0.4.1"

val data = ...

val str = pprint.tokenize(data).mkString
println(str)

您还可以配置宽度、高度、缩进和颜色:

pprint.tokenize(data, width = 80).mkString

文档:https ://github.com/com-lihaoyi/PPrint

于 2016-10-14T15:11:25.327 回答
9

这是我的解决方案,它极大地改进了http://www.lihaoyi.com/PPrint/处理案例类的方式(参见https://github.com/lihaoyi/PPrint/issues/4)。

例如它打印这个: 在此处输入图像描述

对于这样的用法:

  pprint2 = pprint.copy(additionalHandlers = pprintAdditionalHandlers)

  case class Author(firstName: String, lastName: String)
  case class Book(isbn: String, author: Author)
  val b = Book("978-0486282114", Author("first", "last"))
  pprint2.pprintln(b)

代码:

import pprint.{PPrinter, Tree, Util}
object PPrintUtils {
  // in scala 2.13 this would be even simpler/cleaner due to added product.productElementNames
  protected def caseClassToMap(cc: Product): Map[String, Any] = {
    val fieldValues = cc.productIterator.toSet
    val fields = cc.getClass.getDeclaredFields.toSeq
      .filterNot(f => f.isSynthetic || java.lang.reflect.Modifier.isStatic(f.getModifiers))
    fields.map { f =>
      f.setAccessible(true)
      f.getName -> f.get(cc)
    }.filter { case (k, v) => fieldValues.contains(v) }
      .toMap
  }

  var pprint2: PPrinter = _

  protected def pprintAdditionalHandlers: PartialFunction[Any, Tree] = {
    case x: Product =>
      val className = x.getClass.getName
      // see source code for pprint.treeify()
      val shouldNotPrettifyCaseClass = x.productArity == 0 || (x.productArity == 2 && Util.isOperator(x.productPrefix)) || className.startsWith(pprint.tuplePrefix) || className == "scala.Some"

      if (shouldNotPrettifyCaseClass)
        pprint.treeify(x)
      else {
        val fieldMap = caseClassToMap(x)
        pprint.Tree.Apply(
          x.productPrefix,
          fieldMap.iterator.flatMap { case (k, v) =>
            val prettyValue: Tree = pprintAdditionalHandlers.lift(v).getOrElse(pprint2.treeify(v))
            Seq(pprint.Tree.Infix(Tree.Literal(k), "=", prettyValue))
          }
        )
      }
  }

  pprint2 = pprint.copy(additionalHandlers = pprintAdditionalHandlers)
}

// usage
pprint2.println(SomeFancyObjectWithNestedCaseClasses(...))
于 2019-07-17T16:26:05.017 回答
7

就像解析器组合器一样,Scala 已经在标准库中包含了漂亮的打印机组合器。(注意:从 Scala 2.11 开始,该库已弃用。类似的漂亮打印库是kiama开源项目的一部分)。

如果您需要执行“反射”的解决方案,或者您想明确构建打印机,您并没有在您的问题中明确地说出来。(尽管您的“额外问题”暗示您可能需要“反思”解决方案)

无论如何,如果您想使用普通的 Scala 库开发简单的漂亮打印机,就在这里。以下代码是可复制的。

case class VarDecl(name: String, `type`: String)
case class ClassDecl(name: String, fields: List[VarDecl])

import scala.text._
import Document._

def varDoc(x: VarDecl) =
  nest(4, text("- VarDecl") :/:
    group("name = " :: text(x.name)) :/:
    group("type = " :: text(x.`type`))
  )

def classDoc(x: ClassDecl) = {
  val docs = ((empty:Document) /: x.fields) { (d, f) => varDoc(f) :/: d }
  nest(2, text("ClassDecl") :/:
    group("name = " :: text(x.name)) :/:
    group("fields =" :/: docs))
}

def prettyPrint(d: Document) = {
  val writer = new java.io.StringWriter
  d.format(1, writer)
  writer.toString
}

prettyPrint(classDoc(
  ClassDecl("Complex", VarDecl("Real","float") :: VarDecl("Imag","float") :: Nil)
))

额外的问题:将打印机包装到类型类中以获得更大的可组合性。

于 2013-03-30T15:20:54.877 回答
7
import java.lang.reflect.Field
...

/**
  * Pretty prints case classes with field names.
  * Handles sequences and arrays of such values.
  * Ideally, one could take the output and paste it into source code and have it compile.
  */
def prettyPrint(a: Any): String = {
  // Recursively get all the fields; this will grab vals declared in parents of case classes.
  def getFields(cls: Class[_]): List[Field] =
    Option(cls.getSuperclass).map(getFields).getOrElse(Nil) ++
        cls.getDeclaredFields.toList.filterNot(f =>
          f.isSynthetic || java.lang.reflect.Modifier.isStatic(f.getModifiers))
  a match {
    // Make Strings look similar to their literal form.
    case s: String =>
      '"' + Seq("\n" -> "\\n", "\r" -> "\\r", "\t" -> "\\t", "\"" -> "\\\"", "\\" -> "\\\\").foldLeft(s) {
        case (acc, (c, r)) => acc.replace(c, r) } + '"'
    case xs: Seq[_] =>
      xs.map(prettyPrint).toString
    case xs: Array[_] =>
      s"Array(${xs.map(prettyPrint) mkString ", "})"
    // This covers case classes.
    case p: Product =>
      s"${p.productPrefix}(${
        (getFields(p.getClass) map { f =>
          f setAccessible true
          s"${f.getName} = ${prettyPrint(f.get(p))}"
        }) mkString ", "
      })"
    // General objects and primitives end up here.
    case q =>
      Option(q).map(_.toString).getOrElse("¡null!")
  }
}
于 2016-09-28T20:21:37.087 回答
5

我发现的最好、最简洁的“开箱即用”体验是使用Kiama 漂亮的打印库。它不会在不使用其他组合符的情况下打印成员名称,但只有import org.kiama.output.PrettyPrinter._; pretty(any(data))你有一个很好的开始:

case class ClassDecl( kind : Kind, list : List[ VarDecl ] )
sealed trait Kind
case object Complex extends Kind
case class VarDecl( a : Int, b : String )

val data = ClassDecl(Complex,List(VarDecl(1, "abcd"), VarDecl(2, "efgh")))
import org.kiama.output.PrettyPrinter._

// `w` is the wrapping width. `1` forces wrapping all components.
pretty(any(data), w=1)

产生:

ClassDecl (
    Complex (),
    List (
        VarDecl (
            1,
            "abcd"),
        VarDecl (
            2,
            "efgh")))

请注意,这只是最基本的示例。Kiama PrettyPrinter 是一个非常强大的库,具有一组丰富的组合器,专为智能间距、换行、嵌套和分组而设计。很容易调整以满足您的需求。截至本文发布时,它在 SBT 中可用:

libraryDependencies += "com.googlecode.kiama" %% "kiama" % "1.8.0"
于 2015-07-09T13:04:36.943 回答
4

使用反射

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object CaseClassBeautifier  {
  def getCaseAccessors[T: TypeTag] = typeOf[T].members.collect {
    case m: MethodSymbol if m.isCaseAccessor => m
  }.toList

  def nice[T:TypeTag](x: T)(implicit classTag: ClassTag[T]) : String = {
    val instance = x.asInstanceOf[T]
    val mirror = runtimeMirror(instance.getClass.getClassLoader)
    val accessors = getCaseAccessors[T]
    var res = List.empty[String]
    accessors.foreach { z ⇒
      val instanceMirror = mirror.reflect(instance)
      val fieldMirror = instanceMirror.reflectField(z.asTerm)
      val s = s"${z.name} = ${fieldMirror.get}"
      res = s :: res
    }
    val beautified = x.getClass.getSimpleName + "(" + res.mkString(", ") + ")"
    beautified
  }
}
于 2016-02-21T13:23:25.750 回答
3

这是@F 的无耻复制粘贴。P 自由地,但是

  • 我添加了缩进功能
  • 稍作修改,以使输出具有正确的 Scala 样式(并且将为所有原始类型编译)
  • 修复了字符串文字错误
  • 添加了对java.sql.Timestamp(因为我经常在 Spark 中使用它)

多田!

// Recursively get all the fields; this will grab vals declared in parents of case classes.
  def getFields(cls: Class[_]): List[Field] =
    Option(cls.getSuperclass).map(getFields).getOrElse(Nil) ++
      cls.getDeclaredFields.toList.filterNot(f =>
        f.isSynthetic || java.lang.reflect.Modifier.isStatic(f.getModifiers))

  // FIXME fix bug where indent seems to increase too much
  def prettyfy(a: Any, indentSize: Int = 0): String = {
    val indent = List.fill(indentSize)(" ").mkString

    val newIndentSize = indentSize + 2
    (a match {
      // Make Strings look similar to their literal form.
      case string: String =>
        val conversionMap = Map('\n' -> "\\n", '\r' -> "\\r", '\t' -> "\\t", '\"' -> "\\\"", '\\' -> "\\\\")
        string.map(c => conversionMap.getOrElse(c, c)).mkString("\"", "", "\"")
      case xs: Seq[_] =>
        xs.map(prettyfy(_, newIndentSize)).toString
      case xs: Array[_] =>
        s"Array(${xs.map(prettyfy(_, newIndentSize)).mkString(", ")})"
      case map: Map[_, _] =>
        s"Map(\n" + map.map {
          case (key, value) => "  " + prettyfy(key, newIndentSize) + " -> " + prettyfy(value, newIndentSize)
        }.mkString(",\n") + "\n)"
      case None => "None"
      case Some(x) => "Some(" + prettyfy(x, newIndentSize) + ")"
      case timestamp: Timestamp => "new Timestamp(" + timestamp.getTime + "L)"
      case p: Product =>
        s"${p.productPrefix}(\n${
          getFields(p.getClass)
            .map { f =>
              f.setAccessible(true)
              s"  ${f.getName} = ${prettyfy(f.get(p), newIndentSize)}"
            }
            .mkString(",\n")
        }\n)"
      // General objects and primitives end up here.
      case q =>
        Option(q).map(_.toString).getOrElse("null")
    })
      .split("\n", -1).mkString("\n" + indent)
  }

例如

case class Foo(bar: String, bob: Int)

case class Alice(foo: Foo, opt: Option[String], opt2: Option[String])

scala> prettyPrint(Alice(Foo("hello world", 10), Some("asdf"), None))
res6: String =
Alice(
  foo = Foo(
    bar = "hello world",
    bob = 10
  ),
  opt = Some("asdf"),
  opt2 = None
)
于 2019-02-08T14:12:37.847 回答
1

如果您使用 Apache Spark,您可以使用以下方法打印您的案例类:

def prettyPrint[T <: Product : scala.reflect.runtime.universe.TypeTag](c:T) = {
  import play.api.libs.json.Json
  println(Json.prettyPrint(Json.parse(Seq(c).toDS().toJSON.head)))
}

这为您的案例类实例提供了格式良好的 JSON 表示。确保sparkSession.implicits._已导入

例子:

case class Adress(country:String,city:String,zip:Int,street:String) 
case class Person(name:String,age:Int,adress:Adress) 
val person = Person("Peter",36,Adress("Switzerland","Zürich",9876,"Bahnhofstrasse 69"))

prettyPrint(person)

给出:

{
  "name" : "Peter",
  "age" : 36,
  "adress" : {
    "country" : "Switzerland",
    "city" : "Zürich",
    "zip" : 9876,
    "street" : "Bahnhofstrasse 69"
  }
}
于 2020-01-09T08:09:46.010 回答
0

我建议使用您选择的测试框架的 AssertEquals 中使用的相同打印。我正在使用Scalameta并且 成功munit.Assertions.munitPrint(clue: => Any): String了。我可以将嵌套类传递给它,并以适当的缩进查看整个树。

于 2021-09-27T18:50:28.103 回答