如何使用函数链将初始值从过滤后的列表传递给foldLeft?

问题描述 投票:0回答:2

说我有一个

List
。在某些条件下我首先
filter
。现在我想将初始值从这个过滤数组传递到
foldLeft
,同时将两者链接在一起。有办法做到吗?

例如:

scala> val numbers = List(5, 4, 8, 6, 2)
val numbers: List[Int] = List(5, 4, 8, 6, 2)

scala> numbers.filter(_ % 2 == 0).foldLeft(numbers(0)) { // this is obviously incorrect since numbers(0) is the value at index 0 of the original array not the filtered array
     |   (z, i) => z + i
     | }
val res88: Int = 25
scala functional-programming
2个回答
7
投票

您可以对过滤结果进行模式匹配以获得列表的第一个元素(头)和其余元素(尾):

val numbers = List(5, 4, 8, 6, 2)

val result = numbers.filter(_ % 2 == 0) match {
  case head :: tail => tail.foldLeft(head) {
        (z, i) => z + i
  }
   // here you need to handle the case, when after filtering there are no elements, in this case, I just return 0
  case Nil => 0
}

你也可以只使用reduce:

numbers.filter(_ % 100 == 0).reduce {
   (z, i) => z + i
}

但是如果过滤后列表为空,它会抛出异常。


0
投票
import io.circe.generic.auto._
import io.circe.parser
import io.circe.syntax._
import io.circe.Json

val jsonStr = """{"Fieldalreadythere": {}}"""

val jsonParse = parser.parse(jsonStr)


val listOfFields: List[String] = List("A.B.C", "AA.BB")

val listOfSplitFields = listOfFields.map(_.split("\\.").toList)


def makeJson(list: List[String]): Json = {
  list match {
    case h :: Nil => Json.fromFields(List(("3", Json.fromString("33"))))
    case h :: t => Json.fromFields(List(h -> makeJson(t)))
    case Nil => Json.fromFields(Nil)
  }
}


val originalJson = jsonParse match {
       case Right(value) => value.asObject
       case Left(error) => throw error
    }


val updateJsons = listOfSplitFields.map(makeJson(_))
updateJsons.foldLeft(originalJson.asJson)(_.deepMerge(_))
© www.soinside.com 2019 - 2024. All rights reserved.