如何分层“嵌套”使用 Haskell 漂亮打印进行缩进

发布于 2024-11-03 03:09:57 字数 510 浏览 4 评论 0原文

我想使用 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,当前缩进级别。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤蝉 2024-11-10 03:09:57

您的意思是递归调用 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

因此您可能需要列出更多代码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文