我有以下scala代码:

val gates = varNode.getGates()
val inMsgs = gates.map(g => g.getEndGate.getMessage())
val variableMarginal = inMsgs.reduceLeft((msg1, msg2) => msg1 * msg2)


这与C ++中的以下内容是否相同(假设我们知道类型,并且所使用的基础C ++容器是向量)?

std::vector<Gate *> gates = varNode.getGates();
// Assume that the first gate always has a valid message
double marginal = gates[0]->getEndGate()->getMessage();
for (int i = 1; i < gates.size(); ++i)
    marginal *= gates[i]->getEndGate()->getMessage();


我对reduceLeft函数感到困惑。无法理解它的作用。

[编辑] Gate类的定义如下:

sealed abstract class Gate(initialMsg: SingleFactor) {

type END_GATE <: Gate

private var endGate: Option[END_GATE] = None

private var message: SingleFactor = initialMsg
private var oldMessage: SingleFactor = initialMsg
def setEndGate(gate: END_GATE) { endGate = Some(gate) }
def getEndGate(): END_GATE = endGate.get

def setMessage(newMessage: SingleFactor, msgIndex: Long) {
    oldMessage = message
    message = newMessage
}
def getMsgIndex(): Long = msgIndex
def getMessage(): SingleFactor = message
def getOldMessage(): SingleFactor = oldMessage
}

最佳答案

据我所知,您需要实现SingleFactor,并知道它的*运算符是否未重载,然后您可以推断出reduceLeft在做什么。

我假设inMsgs是映射操作完成后(通过.getMessage())的SingleFactor元素的向量。

reduceLeft将获取第一个SingleFactor,然后对第二个SingleFactor使用*运算符,其结果将再次对第三个SingleFactor使用*运算符,依此类推,从而产生一个值,该值将存储在variableMarginal中。

有关reduceLeft的一些用法示例,您可以阅读以下内容:http://alvinalexander.com/scala/scala-reduceleft-examples

要诊断reduce在做什么,您还可以将reduceLeft调用更改为以下内容:(假设您能够执行给定的Scala代码)

# the semicolons are not needed but are added in case you copy paste/single line the code
val variableMarginal = inMsgs.reduceLeft((msg1, msg2) => {
    val result = msg1 * msg2;
    println("msg1: "+ msg1 + " msg2: "+ msg2 + " result: "+result);
    result })


我认为您可以使用累加来“模拟” C ++中的reduceLeft(可以在此处找到API:http://en.cppreference.com/w/cpp/algorithm/accumulate
在这种情况下,您提供的BinaryOperation与Scala的* SingleFactor操作相同。

08-26 19:42