Scala:以功能方式迭代和累积时避免var(无var)
我需要帮助才能找到正确的Scala方法,这将使该代码更具功能性和不可变化。
def findMinTime(str: String, timeByCar: Int): Int = {
var myTime = timeByCar
var minTime = timeByCar
str.reverse.foreach { l =>
if (l == 'A') myTime += 3 else myTime -= 2
if (myTime < minTime) minTime = myTime
}
minTime
}
I need help to find the right Scala approach that will make this code more functional and less mutable.
def findMinTime(str: String, timeByCar: Int): Int = {
var myTime = timeByCar
var minTime = timeByCar
str.reverse.foreach { l =>
if (l == 'A') myTime += 3 else myTime -= 2
if (myTime < minTime) minTime = myTime
}
minTime
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
foldleft
是一种方法,当逻辑简单明了时,很有用。但是通常,在Scala中,这种任务的首选工具是(尾部)递归:`
foldLeft
is one way, useful when logic is simple and concise. But in general the go-to tool for this kind of tasks in scala is (tail) recursion:`
这是使用
foldleft
的解决方案。我们将两个变量存储在每个字符(mytime
和mintime
)之后,我们需要修改,将其存储在元组中。Here's a solution using
foldLeft
. We store the two variables we need to modify after each character (myTime
andminTime
) in a tuple as the accumulator.