Deden Bangkit - 4 months ago 29

Scala Question

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(

aRowcol.take(i).head.head,

aRowcol.take(i).head(1),

aAlpha(aRowcol.take(i).head.head)(aRowcol.take(i).head(1))}

.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`

`aAlpha`

`i++`

Answer

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(
aRowcol(i).head.head,
aRowcol(i).head(1),
aAlpha(aRowcol(i).head.head)(aRowcol(i).head(1))) }
.toList
```

Which works as you expect; But above is a similar yet simpler version.