gpt4 book ai didi

ruby - 在 Ruby 中漂亮地打印树数据结构

转载 作者:数据小太阳 更新时间:2023-10-29 07:00:00 25 4
gpt4 key购买 nike

我正在构建一个编译器,并在其中生成一棵树来表示传入的源程序。我想展示这是一棵时尚的树,以便我可以向任何感兴趣的人展示程序的结构.

现在我只是像这样在一行中打印树:

ProgramNode -> 'Math' BlockNode -> DeclarationNode -> ConstantDeclarationNode -> const ConstantListNode -> [m := 7, ConstantANode -> [n := StringLiteralNode -> ""TEST"" ]] ; 

我想要的是这样的:

   ProgramNode 
/ \
'Math' BlockNode
|
DeclarationNode
|
ConstantDeclarationNode ------------------------------
/ \ |
const ConstantListNode |
/ | \ \ |
m := 7 ConstantANode |
/ | \ |
n := StringLiteralNode |
/ | \ |
" TEST " ;

我还没有真正使用过 Ruby 中的树,它们通常是如何表示的?

如有任何帮助,我们将不胜感激。

最佳答案

这种 pretty-print 需要相当多的数学知识。此外,不清楚如果树对于控制台窗口来说太宽了会发生什么。我不知道有任何现有的库可以做到这一点。我个人使用awesome_print .

tree = {'ConstantDeclarationNode' => ['const',
'ConstantListNode' => ['m', ':=', '7']]}

require 'awesome_print'

ap tree
# >> {
# >> "ConstantDeclarationNode" => [
# >> [0] "const",
# >> [1] {
# >> "ConstantListNode" => [
# >> [0] "m",
# >> [1] ":=",
# >> [2] "7"
# >> ]
# >> }
# >> ]
# >> }

它有很多选项,检查一下!

关于ruby - 在 Ruby 中漂亮地打印树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11103613/

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