0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer! I've tried to left the second case blank to eliminate 6 and 4. But why it bring blank list to r? so the result become r: List[Any] = List(List(8, 8), List(7, 7), (), (), List(9, 9))
Because you return an empty value, or more technically, a Unit value. Try filtering first and then map: (aList zip aUpdate).filter { case (list, update) => (list.contains(update)) }.map { case (list, update) => update :: list } Note that you can also use withFilter instead of filter to avoid creating the intermediate collection (that is, you will filter and map in one pass that way; withFilter simply restricts the domain for the upcoming map).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.