Reputation: 3781
I am the beginner of Haskell, and I want to make a pretty printing with data structures in Haskell.
I have the following data structure:
I want to print the following value:
int a(int b, int* c){
return b + *c;
}
by using the following function types:
pFunc :: f -> document
putStrLn $ pretty 40 $ pFunc fun
fun =("a", TInt, [(TInt, "b"),(TPtr TInt, "c")]
, [SReturn (EBinOp "+" (EIdent "b") (EUnOpPre "*" (EIdent "c")))])
document
data structure is as the following:
But honestly I don't have any idea. I have many similar simple printings. If I can have an idea about this printing, the remaining one won't be a problem.
But might be the shortest way to print the value above by using document
data type?
Upvotes: 0
Views: 1054
Reputation: 12749
Write a pretty-printer function for each of the types in the abstract-syntax-tree. Each function will have type:
pretty<Foo> :: <Foo> -> Document
where you replace <Foo>
with the type name. Work bottom up, so you can test each function as you write it. i.e. implement the pretty-printer for Type
first, since it is needed by the pretty-printer for Stmt
and f
(which should be called Func
or something).
For instance:
prettyType :: Type -> Document
prettyType TVoid = text "void"
prettyType TInt = text "int"
prettyType TFloat = text "float"
prettyType TChar = text "char"
prettyType TPtr t = prettyType t <> text "*"
prettyType TStruct s = text "struct" <+> text s
Follow the same pattern for each of Exp
, Stmt
, Case
, and Func
.
Upvotes: 1