Reputation: 598
How do I append this list:
val aList = List(List(8),List(7),List(6),List(4),List(9))
based on:
val aUpdate = List(8,7,4,2,9)
and the output should be:
val aList = List(List(8,8), List(7,7),List(6),List(4),List(9,9))
I had expected the following code to work:
val aList = for (i <- 1 to 4) aList map (_(i)) {
case if aList map (_(i)) contains aUpdate(i) => ++ List(map.aUpdate(i))
Anyone could tell me what is the valid argument for the output? and please explain the detail how it works.
Upvotes: 0
Views: 44
Reputation: 9698
Your code is not really valid. There are couple of things missing, such as pattern identifier after case
, list value before concatenation, closing bracket etc.
Here's one way to do it:
val r = (aList zip aUpdate).map {
case (list, update) if (list.contains(update)) => update :: list
case (list, update) => list
}
// result: List(List(8, 8), List(7, 7), List(6), List(4), List(9, 9))
Zipping one list with another results in a list of pairs, where n-th pair consists of n-th element from the first list and n-th element from the second list. Now you can easily do what you want; if element that comes from aList
contains the element that comes from aUpdate
then add it to the list, otherwise (note that second case has same identifiers, but no condition) just return the element from aList
.
Upvotes: 1