Search code examples
haskellpretty-print

How to hierarchically "nest" indents with Haskell pretty-printing


I want to print out an AST, using Haskell Pretty package.

It all works well, but nested constructs don't indent properly.

I do something like this:

draw :: Pretty a => a -> String
draw = render.pretty

pretty (Letin  d  c ) =  text "let" <+> text (draw d) $$
                         nest 4 (text "in" <+> text (draw c))

but the results are like this:

let Const  x := 2
    in let Var  y := Int 
    in y = 3; let Var  z := Int 
    in z = 0; z = z + 1 

It seems that the nest levels are not inherited, so all are absolute on the +4 margin, instead of successively indented at each level, i.e. +4 relative to their parent, the current indent level.


Solution

  • Do you mean to call pretty recursively? I can't tell from your question.

    A quick test to try to reproduce what you've done:

    import Text.PrettyPrint
    
    data Letin = Letin String (Maybe Letin)
    
    draw = show
    
    pretty (Letin  d  c ) =
         text "let" <+> text (draw d) $$
            nest 4 (text "in" <+> case c of Nothing -> text "empty";
                                            Just c' -> pretty c')
    

    Results in, as expected:

    let "x"
        in let "y"
               in empty
    

    So you may have to list more code.