|
| |
| Navigation |
Synopsis A Lisp pretty printer.
Description The purpose of a pretty printer is to convert an internal structure to text.
We define here the simplest possible solution:
module demo::lang::Lisra::Pretty
import demo::lang::Lisra::Runtime;
// Pretty print: transform an Lval to a string
public str pretty(Integer(n)) = "<n>";
public str pretty(Atom(name)) = name;
public str pretty(List(elms*)) = "( <for(e <- elms){><pretty(e)> <}>)";
public str pretty(Closure(Result(list[Lval] args, Env env))) = "Closure(<args>)";
Compare the definition of pretty with that of parse:
Lval parse(str txt); str pretty(Lval x);For a well-designed pair of parse/pretty functions, the latter is the inverse of the former.
In other words, for every L the following should hold:
parse(pretty(L)) == L
Examples
rascal>import demo::lang::Lisra::Runtime; ok rascal>import demo::lang::Lisra::Pretty; ok rascal>pretty(Integer(42)); str: "42" rascal>pretty(Atom("x")); str: "x" rascal>L = List([Atom("+"), Integer(5), Integer(7)]); Lval: List([ Atom("+"), Integer(5), Integer(7) ]) rascal>pretty(L); str: "( + 5 7 )"Now let's explore whether pretty is indeed the inverse of parse:
rascal>import demo::lang::Lisra::Parse; ok rascal>parse(pretty(L)) == L; bool: true |