gpt4 book ai didi

list - 如何以功能样式从列表中添加选择性行的值?

转载 作者:行者123 更新时间:2023-12-03 18:16:50 24 4
gpt4 key购买 nike

我以命令式的方式解决了我的问题,但它看起来非常难看。我怎样才能让它更好(更优雅、更简洁、更实用——最后是它的 Scala)。应跳过与前一行具有相同值但具有不同字母的行,应添加行的所有其他值。

val row1 = new Row(20, "A", true)    // add value  
val row2 = new Row(30, "A", true) // add value
val row3 = new Row(40, "A", true) // add value
val row4 = new Row(40, "B", true) // same value as the previous element & different letter -> skip row
val row5 = new Row(60, "B", true) // add value
val row6 = new Row(70, "B", true) // add value
val row7 = new Row(70, "B", true) // same value as the previous element, but the same letter -> add value

val rows = List(row1, row2, row3, row4, row5, row6, row7)

var previousLetter = " "
var previousValue = 0.00
var countSkip = 0

for (row <- rows) {
if (row.value == previousValue && row.letter != previousLetter) {
row.relevant = false
countSkip += 1
}
previousLetter = row.letter
previousValue = row.value
}

// get sum
val sumValue = rows.filter(_.relevant == true).map(_.value) reduceLeftOption(_ + _)
val sum = sumValue match {
case Some(d) => d
case None => 0.00
}

assert(sum == 290)
assert(countSkip == 1)

提前致谢

特威斯顿

最佳答案

(rows.head :: rows).sliding(2).collect{ 
case List(Row(v1,c1), Row(v2,c2)) if ! (v1 == v2 && c1 != c2) => v2 }.sum

关于list - 如何以功能样式从列表中添加选择性行的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5035038/

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