Deden Bangkit - 1 year ago 80
Scala Question

# Create and Append list based on other list member in Scala

I have list of Integer like this:

``````val aRowcol: List[List[Int]]] =
List(List(0, 0), List(0, 1), List(0, 2)),
List(List(1, 0), List(1, 1), List(1, 2)),
List(List(2, 0), List(2, 1), List(2, 2)),
List(List(0, 0), List(1, 1), List(2, 2)),
List(List(2, 0), List(1, 1), List(0, 2)),
List(List(1, 0), List(0, 1), List(0, 2)),
List(List(1, 0), List(2, 1), List(2, 2))

val aAlpha: List[List[String]] = List(
List("a","b","c","d"),
List("e","f","g","h"),
List("i","j","k","l","m"))

val i = 4
val resNum:List[List[Int,String]] = (0 to i) {
_map => List(
.toList
``````

But the result I want for val resNum is:

```List( List(0,0,"a"), List(1,0,"e"), List(2,0,"i"), List(0,0,"a"), List(2,0,"i"))```

(0,0) means first row first column, we have "a" on that possition, so
`i`
will define how many
`aAlpha`
we will have. I think it will be much easier if we do
`i++`
, but you know that we couldn't do i++ in scala.

I'm guessing that you want to treat the first element in each "list of lists" in `aRowcol` as the "coordinates" of a letter in `aAlpha`, and want to append that letter to each of these "first elements".

If so:

``````val result: List[List[Any]] = aRowcol.take(5) // only 5 first rows
.map(_.head)   // first List(i, j) only, the rest is ignored
.map { case List(i, j) => List(i, j, aAlpha(i)(j)) } // append the right letter to list

result.foreach(println)
// List(0, 0, a)
// List(1, 0, e)
// List(2, 0, i)
// List(0, 0, a)
// List(2, 0, i)
``````

If that's not what you meant - please clarify.

EDIT: as for your version - it can work (and achieve the same goal) with a few fixes:

• `list.take(i)` doesn't return the i-th element, it returns a list with the first i elements, I think you're trying to use `list.apply(i)` which returns the i-th element, or it's shorthand version: `list(i)`
• If you want to map the numbers 0..4 - call `map` and then name the argument of the anonymous function you pass `i` - don't use a `var` declared outside of the method and expect it to increment

With these corrections (and some more), your version becomes:

``````val resNum: List[List[Any]] = (0 to 4).map { i =>
List(