Combining two lists in Scala

后端 未结 8 841
北海茫月
北海茫月 2021-01-04 00:58

From 2 lists of the form List[(Int, String):

l1 = List((1,\"a\"),(3,\"b\"))
l2 = List((3,\"a\"),(4,\"c\"))

how can I combine t

8条回答
  •  星月不相逢
    2021-01-04 01:56

    Note that with this solution, the lists are traversed twice.

    val l3 = (l1 zip l2).foldRight(List[(Int, String)]()) {
      case ((firstPair @ (firstNumber, firstWord),
            secondPair @ (secondNumber, secondWord)),
            result) =>
        if (firstWord == secondWord)
          ((firstNumber + secondNumber), firstWord) :: result
        else
          firstPair :: secondPair :: result
    }
    

提交回复
热议问题