Haskell 中的漂亮打印:在打印嵌套元组时,破坏外部组。

3
我想使用Haskell和(目前)wl-pprint-annotated(愿意切换到其他库)来漂亮地打印AST。
如何使渲染器优先选择外部组的softlines而不是内部组的softlines?
最小示例
以元组((1234, 5678), (abcd, efgh))为例。
我想要的输出:
// line width: 10
(
  (
    1234,
    5678
  ),
  (
    abcd,
    efgh
  )
)

// line width: 16
(
  (1234, 5678),
  (abcd, efgh)
)

// line width: 32
((1234, 5678), (abcd, efgh))

我得到的输出:
// line width: 10
((1234,
    5678),
  (abcd,
    efgh))

// line width: 16
((1234, 5678), (
    abcd, efgh))

// line width: 32
((1234, 5678), (abcd, efgh))

代码:

module Main where
import qualified Prelude
import Prelude hiding((<>))

import Text.PrettyPrint.Annotated.WL 

main :: IO ()
main = do
  putStrLn $ pp 10
  putStrLn $ pp 16
  putStrLn $ pp 32

pp w = "// line width: " ++ show w ++ "\n" ++
       display (renderPretty 1.0 w doc) ++ "\n"

doc = pair (pair (text "1234") (text "5678"))
           (pair (text "abcd") (text "efgh"))

pair x y = group (nest 2 (lparen <//> x <> comma </> y) <//> rparen)

2
我不知道为什么这个代码能正常工作或者它的健壮性如何,但是它似乎可以在您的示例上产生您想要的输出。pair x y = group (nest 2 (lparen <##> x <> comma <#> y) <##> rparen) - ekim boran
@ekimboran 太棒了!它不仅在我的最小示例中起作用,而且在更复杂的测试套件中也能正常运行。现在我重新阅读了文档,发现它以一种让我在浏览时感到困惑的方式描述了我想要的效果。 - Random Citizen
2
@ekimboran,您是否想创建一个答案,以便我可以将其标记为解决方案? - Random Citizen
2个回答

1
pair x y = group (nest 2 (lparen <##> x <> comma <#> y) <##> rparen)

1

当ekim发现时,我把</><#>混淆了。

我发现文档有些令人困惑,所以让我稍微澄清一下。

首先,运算符</><#>只是linesoftline的简写。 请参见definitions

x </> y = x <> softline <> y
x <#> y = x <> line <> y

我的问题是我在使用 softline 时,我想要的是 line。 < h4 > linesoftline 的共同点

当整行符合页面时,两者都会被打印为空格。当整行不适合页面时,两者都会被替换为换行符。

linesoftline 的区别

当一个组不适合页面时,整个组的所有 line 都会被替换为换行符。这就是我想要的行为。

当一行文字超出页面时,仅替换最后一个适合页面的 软换行 ,而不是整个组。这就像我们文本编辑器中的自动换行:只在最后一个适合页面的单词后面断行。例如:
doc = paragraph p1
paragraph = foldr (</>) mempty . map text . words
p1 = "I want to pretty print an AST using Haskell and (currently) wl-pprint-annotated (willing to switch to a different library)."

is printed as

I want to pretty print an AST using Haskell and
(currently) wl-pprint-annotated (willing to
switch to a different library).

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接