如何使班级成为Scala中两个链接列表的成员? [英] How to make a class a member of two linked lists in Scala?

查看:48
本文介绍了如何使班级成为Scala中两个链接列表的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种感觉,我想念这里很明显的东西.

I have a feeling I'm missing something very obvious here.

作为学习练习,我正在将用 Java 编写的编译器生成器转换为 Scala.

I'm converting a compiler generator written in Java into Scala as a learning exercise.

它不是真正用Java编写的,似乎是音译为C.

It's not really written in Java, it seems to be transliterated C.

在程序的一部分中,有节点.每个节点都是两个链接列表的一部分,并且存在一些字段,这些字段引用每个链接列表中的下一项(称为跨"和下").各种方法遍历这些列表(一个或两个),并对每个访问的节点执行操作.

In one part of the program, there are Nodes. Each node is part of two linked lists, and there are fields that are references to the next item in each of the linked lists (call these "across" and "down"). Various methods traverse these lists, either one of them or both of them and do things to each visited node.

我想使用Scala的集合而不是这些显式的引用,因为有很多样板代码遍历并向这些列表添加内容.我该怎么做呢?列表是可变的,所以我想使用可变列表

I'd like to use Scala's collections instead of these explicit references, since there's a lot of boilerplate code traversing and adding stuff to these lists. How do I do this? The lists are quite changeable so I want to use mutable lists

我想我不想要Node的链表,因为每个Node都需要知道其下一个(或向下)邻居的邻居,而不管我如何到达此节点,因此我需要能够任一列表的节点.

I think I don't want a linked list of Node, because each Node needs to know what its next across (or down) neighbor is, regardless of how I got to this node so I need to be able to go from Node to either list.

我可以从LinkedList继承,但是我需要做两次(一次跨过一次,一次向下一次).

I could inherit from LinkedList, but I need to do that twice (once for across and once for down).

我可以有两个内部类(acrosslist和downlist),每个类都是LinkedList的实例,但是它们可以是LinkedList [Node]吗?我无法理解它的工作方式,因为该列表的下一个引用必须是node.acrosslist.next(例如),而对于LinkedList,它只是下一个".

I could have two inner classes (acrosslist and downlist) each an instance of LinkedList, but can they be LinkedList[Node]? I can't get my head around how this would work, as the 'next reference for the list would need to be node.acrosslist.next (say) and for LinkedList it's just "next".

所以,请指出显而易见的(或者如果不是显而易见的话)如何使它工作!

So, please point out the obvious, or if not obvious, how I get this to work!

推荐答案

为什么不将自己链接起来,然后在各个方向上创建迭代器?

Why don't you link things up yourself, and then create iterators in each direction?

class Node(var left: Node, var down: Node) {
  def iterateDown = new Iterator[Node] {
    private[this] var current = this
    def hasNext = down ne null
    def next = { current = down; current }
  }
  def iterateLeft = new Iterator[Node] {
    private[this] var current = this
    def hasNext = left ne null
    def next = { current = left; current }
  }
}

这篇关于如何使班级成为Scala中两个链接列表的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆