gpt4 book ai didi

haskell - pretty-print : Linebreak on narrow margin, 否则为空

转载 作者:行者123 更新时间:2023-12-04 03:39:55 24 4
gpt4 key购买 nike

我正在使用 prettyprinter 图书馆到prettyprint foo(bar, baz) ,当边距太窄时,我希望它看起来像:

foo(
bar,
baz)
我怎么做?
到目前为止我最好的尝试:
> import Prettyprinter
> import Prettyprinter.Util
> let commas = punctuate comma

-- 'sep' and 'nest' seem to go well together, but the result lacks the linebreak
> putDocW 10 ("foo" <> parens (nest 2 (sep (commas ["bar", "baz"]))))
foo(bar,
baz)

-- Using 'line'' inside 'nest' almost does the trick
> putDocW 10 ("foo" <> parens (nest 2 (line' <> sep (commas ["bar", "baz"]))))
foo(
bar,
baz)

-- Except 'line'' doesn't seem "mempty" enough
> putDocW 20 ("foo" <> parens (nest 2 (line' <> sep (commas ["bar", "baz"]))))
foo(
bar, baz)
我以为我想要的是 line' 因为提到 mempty :

line' is like line, but behaves like mempty if the line break is undone by group (instead of space).


但也许我误解了“由 group 撤消”的作用。
其他的( linesoftlinesoftline' )似乎都没有给出更好的结果。

最佳答案

我不相信这是“正确”的方式,但这里有一个方法:

hcat
[ "prefix"
, nest 2 $ cat
$ "("
: punctuate (flatAlt "," ", ")
[ "first"
, "second"
, "third"
]
, ")"
]
也就是说,将左括号和标点元素的串联卡在前缀之后,根据它们是否折叠,将它们分开有或没有尾随空格,并粘贴在右括号上。
或者,您可以制作自己的 encloseSep 变体在末尾而不是开头添加分隔符,并在 cat 中包含开始分隔符:
encloseSepEnd
:: Doc ann -> Doc ann -> Doc ann -> [Doc ann] -> Doc ann
encloseSepEnd open close sep docs = case docs of
[] -> open <> close
[doc] -> open <> doc <> close
_ -> cat (open : suffixReverse (close : repeat sep) docs)

suffixReverse
:: (Foldable t, Semigroup a)
=> [a] -> t a -> [a]
suffixReverse separators
= snd . foldr go (separators, [])
where
go doc (sep : seps, acc) = (seps, doc <> sep : acc)
hcat
[ "prefix"
, nest 2 $ encloseSepEnd "(" ")" ", "
["first", "second", "third"]
]
除此之外,老实说,我发现我总是必须替换括号函数,例如 parens用它们单独的部分来达到我想要的结果,以及 group从不表现得像我希望的那样。

关于haskell - pretty-print : Linebreak on narrow margin, 否则为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66235940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com