Scala - how to print case classes like (pretty printed) tree

前端 未结 10 1868
情歌与酒
情歌与酒 2020-12-07 22:35

I\'m making a parser with Scala Combinators. It is awesome. What I end up with is a long list of entagled case classes, like: ClassDecl(Complex,List(VarDecl(Real,float

10条回答
  •  心在旅途
    2020-12-07 22:42

    The nicest, most concise "out-of-the" box experience I've found is with the Kiama pretty printing library. It doesn't print member names without using additional combinators, but with only import org.kiama.output.PrettyPrinter._; pretty(any(data)) you have a great start:

    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)
    

    Produces:

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

    Note that this is just the most basic example. Kiama PrettyPrinter is an extremely powerful library with a rich set of combinators specifically designed for intelligent spacing, line wrapping, nesting, and grouping. It's very easy to tweak to suit your needs. As of this posting, it's available in SBT with:

    libraryDependencies += "com.googlecode.kiama" %% "kiama" % "1.8.0"
    

提交回复
热议问题