【问题标题】:How to hierarchically "nest" indents with Haskell pretty-printing如何使用 Haskell 漂亮打印分层“嵌套”缩进
【发布时间】:2011-04-22 04:45:26
【问题描述】:

我想使用 Haskell Pretty 包打印出一个 AST。

一切正常,但嵌套结构不能正确缩进。

我会这样做:

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

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

但是结果是这样的:

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

似乎嵌套级别不是继承的,因此所有嵌套级别都是绝对的 +4 边距,而不是在每个级别连续缩进,即相对于它们的父级,当前缩进级别 +4。

【问题讨论】:

    标签: haskell pretty-print


    【解决方案1】:

    你的意思是递归调用pretty?从你的问题我看不出来。

    尝试重现您所做的快速测试:

    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')
    

    结果如预期:

    let "x"
        in let "y"
               in empty
    

    所以你可能需要列出更多代码。

    【讨论】:

    • 是的,递归。我遗漏了draw的定义;上面添加的,应该和我想的一样。我的错误是在使用 render.pretty 的“text (draw e)”上递归,而不是直接在“pretty e”上递归。虽然我不知道为什么会破坏它......谢谢!
    猜你喜欢
    • 2016-07-07
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2014-05-18
    • 2012-05-04
    • 2011-09-03
    相关资源
    最近更新 更多