我可以在每个平面图案例中提供说明吗?如果没有,如何增加计数器?
Can I have instructions in each flatmap case? If not, how to increase counter?
我有一个 flatmap
正在经历 Sequence
,我正在使用 case
来识别 Sequence
中的不同元素,并替换元素与其他东西。但是,在某些情况下,我还想增加一个计数器变量。我可以在 case
中放置一条指令吗?看来我不能,因为 case
中的内容将替换 Sequence
中的元素。这可能吗?
这是我试过的代码,但没有用:
var location = 0
code.flatMap {
case Define(label) => Word("") // Return an empty Word, don't increase location
case CodeWord(word) => word; location = location + 4 // Return the Word and increase location by 4
case Use(label) => Word(Assembler.encodeUnsigned(labelToValue(label))); location = location + 4
// Convert label into Seq, then into Word. Increase location.
case BeqBne(bits, label) =>{ // Are brackets necessary?
Word(bits ++ encodeUnsigned(labelToValue(label) - (location + 4))); location = location + 4 }
case _ => require(false, s"Encountered unsupported code $code.");
}
更新 location
变量很重要,因为如您所见,在 case BeqBne(bits, label)
中我需要使用 location
的当前值。我是否应该在 flatmap
之外创建一个函数来完成所有这些工作,然后在 flatmap
内部调用该函数并在每种情况下传递值?
任何建议表示赞赏。
当在代码块中指定多个语句时,最后一个语句用作 return 值。因此您需要先增加位置变量,然后再创建 Word 结果。
例如,更改:
case Use(label) => {
Word(Assembler.encodeUnsigned(labelToValue(label)));
location = location + 4
}
收件人:
case Use(label) => {
location = location + 4;
Word(Assembler.encodeUnsigned(labelToValue(label)));
}
或者如果您需要在创建结果后增加位置然后将结果存储在变量中:
case BeqBne(bits, label) => {
val result = Word(bits ++ encodeUnsigned(labelToValue(label) - (location + 4)));
location = location + 4;
result
}
我有一个 flatmap
正在经历 Sequence
,我正在使用 case
来识别 Sequence
中的不同元素,并替换元素与其他东西。但是,在某些情况下,我还想增加一个计数器变量。我可以在 case
中放置一条指令吗?看来我不能,因为 case
中的内容将替换 Sequence
中的元素。这可能吗?
这是我试过的代码,但没有用:
var location = 0
code.flatMap {
case Define(label) => Word("") // Return an empty Word, don't increase location
case CodeWord(word) => word; location = location + 4 // Return the Word and increase location by 4
case Use(label) => Word(Assembler.encodeUnsigned(labelToValue(label))); location = location + 4
// Convert label into Seq, then into Word. Increase location.
case BeqBne(bits, label) =>{ // Are brackets necessary?
Word(bits ++ encodeUnsigned(labelToValue(label) - (location + 4))); location = location + 4 }
case _ => require(false, s"Encountered unsupported code $code.");
}
更新 location
变量很重要,因为如您所见,在 case BeqBne(bits, label)
中我需要使用 location
的当前值。我是否应该在 flatmap
之外创建一个函数来完成所有这些工作,然后在 flatmap
内部调用该函数并在每种情况下传递值?
任何建议表示赞赏。
当在代码块中指定多个语句时,最后一个语句用作 return 值。因此您需要先增加位置变量,然后再创建 Word 结果。
例如,更改:
case Use(label) => {
Word(Assembler.encodeUnsigned(labelToValue(label)));
location = location + 4
}
收件人:
case Use(label) => {
location = location + 4;
Word(Assembler.encodeUnsigned(labelToValue(label)));
}
或者如果您需要在创建结果后增加位置然后将结果存储在变量中:
case BeqBne(bits, label) => {
val result = Word(bits ++ encodeUnsigned(labelToValue(label) - (location + 4)));
location = location + 4;
result
}