Overview
Overview of Document library
The document library contains code that was developed as part of the Scala standard library but was later deprecated.
We maintain the code mainly because we used it in one of our projects and also as a small and simple test module that we can use to check continuous integration, documentation, cross-scala compilations, tests, and so on.
It consists os a basic pretty-printing library, which was based on Lindig's strict version of Wadler's adaptation of Hughes' pretty-printer derived from Document.scala whose author was Michel Schinz.
You can see the web page for technical documentation.
Further info
- The design of a pretty-printing library by John Hughes, describes the original pretty-printing library in Haskell, PDF
- Strictly Pretty Paper by Christian Lindig, describes a strict implementation of the pretty printing algorithm in OCaml
Example usage
In order to use the library:
import es.weso.document._
Let's declare a simple Tree
case class:
case class Tree(value: String, leaves: List[Tree])
We can define a tree2Doc
function that converts trees to documents as:
def tree2Doc(tree: Tree): Document =
DocText(tree.value) :/: DocNest(1,list2doc(tree.leaves))
def list2doc(ls: List[Tree]): Document =
ls.foldLeft(Document.empty){ case (acc,t) => tree2Doc(t) :/: acc }
In that way, given the following tree:
val myTree = Tree("A", List(Tree("B", List()), Tree("C", List())))
// myTree: Tree = Tree("A", List(Tree("B", List()), Tree("C", List())))
We can convert it to a document as:
val myDoc = tree2Doc(myTree)
// myDoc: Document = DocCons(
// DocText("A"),
// DocCons(
// DocBreak,
// DocNest(
// 1,
// DocCons(
// DocCons(DocText("C"), DocCons(DocBreak, DocNest(1, DocNil))),
// DocCons(
// DocBreak,
// DocCons(
// DocCons(DocText("B"), DocCons(DocBreak, DocNest(1, DocNil))),
// DocCons(DocBreak, DocNil)
// )
// )
// )
// )
// )
// )
Documents can be pretty-printed by using the format
method that requires a Writer
as a parameter:
import java.io._
val writer = new StringWriter()
// writer: StringWriter = A C B
The result of pretty printing to the writer can be seen by running:
myDoc.format(20, writer)
writer.toString
// res1: String = "A C B "