haskell - 在交互式 session 中在 haskell 中漂亮地垂直打印列表

标签 haskell jupyter-notebook ghci pretty-print ihaskell

在 ghci session 中(恰好在 jupyter 内核中),我想在 haskell 中垂直打印一个列表。 (在我的用例中,我正在查看 CSV,因此此列表代表一列数据,我希望显示能够反射(reflect)这一点。)

Prelude> print ["1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666"]
["1111111111","2222222222","3333333333","4444444444","5555555555","6666666666"]

我正在查看 GenericPretty 的文档:

http://hackage.haskell.org/package/GenericPretty

我有这些数据:

import Text.PrettyPrint.GenericPretty

Prelude> toprint = ["1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666"]
Prelude> print toprint -- first, show standard print
["1111111111","2222222222","3333333333","4444444444","5555555555","6666666666"]

我正在尝试漂亮地打印:

Prelude> pretty toprint
"[\"1111111111\",\"2222222222\",\"3333333333\",\"4444444444\",\n \"5555555555\",\"6666666666\"]"

这不太正确。您可以看到它确实添加了一个“\n”,但它并不是在每一行之后,有趣的是它也没有在交互式 session 中执行。它呈现为文本而不是打印。

在 python 中,我会这样做:

>>> from pprint import pprint as pp
>>> print(['1111111111', '2222222222', '3333333333', '4444444444', '5555555555', '6666666666'])
['1111111111', '2222222222', '3333333333', '4444444444', '5555555555', '6666666666']
>>> pp(['1111111111', '2222222222', '3333333333', '4444444444', '5555555555', '6666666666'])
['1111111111',
 '2222222222',
 '3333333333',
 '4444444444',
 '5555555555',
 '6666666666']

在我的 session 中打印的由“\n”分隔的垂直平铺正是我正在寻找的。我该怎么做?

最佳答案

Iavor Diatchki 的 pretty-show 包在这方面做得非常好:https://hackage.haskell.org/package/pretty-show

首先,使用cabal install Pretty-show安装它。然后:

Prelude> import Text.Show.Pretty
Prelude Text.Show.Pretty> putStrLn  $ ppShow ["1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666"]
[ "1111111111"
, "2222222222"
, "3333333333"
, "4444444444"
, "5555555555"
, "6666666666"
]

您甚至可以指示 ghci 自动执行此操作,因此您不必自己调用 ppShow:

Prelude> import Text.Show.Pretty (ppShow, pPrint)
Prelude Text.Show.Pretty> :set -interactive-print pPrint
Prelude Text.Show.Pretty> ["1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666"]
[ "1111111111"
, "2222222222"
, "3333333333"
, "4444444444"
, "5555555555"
, "6666666666"
]

您可以将相关说明放入 .ghci 文件中,这样如果您愿意,此操作就会自动发生。有关详细信息,请参阅此博文:https://teh.id.au/posts/2017/02/13/interactive-print/index.html

关于haskell - 在交互式 session 中在 haskell 中漂亮地垂直打印列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53957624/

相关文章:

Haskell:抽象遗传算法

haskell - 如何使用randomRIO生成无限的随机数列表?

haskell - "monadic application"的更多信息?

python - 如何从 ipywidget 选择小部件中获取值(value)?

haskell - GHC : partially compile Haskell code?

haskell - k -> * 是什么意思?

python-3.x - 根据列值指定直方图的颜色。各个图表保持一致

python - “wget”在 Jupyter Notebook 中无法识别,但在命令行中运行

haskell - 如何针对已编译的包运行 GHCi?

haskell - 如何正确访问 `Constraint` 类型?