gpt4 book ai didi

scala - 算法混合

转载 作者:行者123 更新时间:2023-12-04 19:51:01 24 4
gpt4 key购买 nike

我有一个扩展 Iterator 并对复杂算法建模的类 (MyAlgorithm1)。这样,算法就可以通过Next方法逐步推进。

class MyAlgorithm1(val c:Set) extends Iterator[Step] {
override def next():Step {
/* ... */
}
/* ... */
}

现在我想在第一个算法的每次传递中应用不同的算法 (MyAlgorithm2)。应该插入算法1和2的迭代

class MyAlgorithm2(val c:Set) { /* ... */ }

我怎样才能以最好的方式做到这一点?也许有一些特质?

更新:

MyAlgorithm2 接收一个集合并对其进行转换。 MyAlgorithm1 也是,但是这个比较复杂,需要一步步运行。这个想法是运行 MyAlgoirthm1 的一步,然后运行 ​​MyAlgorithm2。下一步相同。实际上,MyAlgorithm2 简化了集合,可能有助于简化 MyAlgorithm1 的工作。

最佳答案

如前所述,问题可以通过继承或特征来解决。例如:

class MyAlgorithm1(val c:Set) extends Iterator[Step] {
protected var current = Step(c)
override def next():Step = {
current = process(current)
current
}
override def hasNext: Boolean = !current.set.isEmpty
private def process(s: Step): Step = s
}

class MyAlgorithm2(c: Set) extends MyAlgorithm1(c) {
override def next(): Step = {
super.next()
current = process(current)
current
}
private def process(s: Step): Step = s
}

有了 traits,您可以使用 abstract override 做一些事情,但是设计它以便将简化的结果提供给第一个算法可能会更难。

但是,我建议您以错误的方式解决问题。

您可以这样定义您的算法,而不是为扩展迭代器的算法创建类:

class MyAlgorithm1 extends Function1[Step, Step] {
def apply(s: Step): Step = s
}

class MyAlgorithm2 extends Function1[Step, Step] {
def apply(s: Step): Step = s
}

然后可以更容易地定义迭代器:

Iterator.iterate(Step(set))(MyAlgorithm1 andThen MyAlgorithm2).takeWhile(_.set.nonEmpty)

关于scala - 算法混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3128119/

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