Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 489
guthrie Avatar asked Feb 01 '26 01:02

guthrie


1 Answers

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.

like image 168
Don Stewart Avatar answered Feb 02 '26 19:02

Don Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!