在 R 中滚动你自己的链表/树?
我试图理解 R 编程语言的基本概念,但发现这很困难,因为 R 面向统计而不是通用编程。我找不到任何类似于指针/引用的内容。如何在 R 语言中实现链表、搜索树等?
注意:我知道,如果您实际上在 R 中滚动自己的自引用数据结构,那么可能有更好的方法来完成您想要完成的任务。但是,我相信答案将帮助我更好地理解该语言的整体结构和概念。
编辑:关于 Matt Shotwell 的评论,这个问题的要点是我希望在 R 中干净地编写链接列表和树,而不是作为用 C 或其他语言编写的扩展。将其作为扩展或通过解释器的神秘细节来实现它会达不到目的。
I'm trying to wrap my head around the basic concepts of the R programming language and am finding it difficult since R is geared towards statistics instead of general-purpose programming. I can't find anything similar to pointers/references. How would you implement a linked list, search tree, etc. within the R language?
Note: I understand that if you're actually rolling your own self-referential data structures in R, there's probably a better way to accomplish what you're trying to accomplish. However, I believe an answer will help me understand the overall structure and concepts of the language better.
Edit: With regard to Matt Shotwell's comment, the point of this question is that I'm looking to write linked lists and trees cleanly, within R, not as an extension written in C or some other language. Doing it as an extension or by mucking with arcane details of the interpreter defeats the purpose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
R 中的链表可以表示为向量,通常是
列表
。您无需编写特殊代码来引用下一个和上一个项目,因为 R 通过索引为您完成此操作。要将新项目添加到列表中,只需跟踪其长度并分配给下一个项目即可。
由于 R 处理内存的方式,这对于长列表可能效率低下。如果可能,请提前创建列表,并在其内容可用时分配它们。
从列表中删除项目可以通过负索引来完成。
树只是一个包含其他列表的列表。
默认情况下,没有内置的结构强制,例如二叉树的每个节点只有两个子节点。通过 S4 类可以使用更结构化的方法,但这可以在紧要关头完成工作。
A linked list in R can be represented as a vector, typically a
list
. You don't need to write special code to reference the next and previous items, because R does it for you via indexing.To add a new item to the list, just keep track of its length and assign to the next in line.
This can be inefficient for long lists because of the way R handles memory. If possible, create the list in advance, and assign their contents as they become available.
Deleting an item from the list can be accomplished with negative indexes.
A tree is just a list containing other lists.
By default there is no built-in enforcing of the structure, eg only two children per node for a binary tree. More structured approaches are available via S4 classes, but this will do the job in a pinch.