Jordy Huijgens
Jordy Huijgens

Reputation: 23

How can I make a list of tuples in scala in a function?

I am trying to make a list filled with tuples, in a recursive function, so the list can get bigger while iterating. I just don't know how to achieve this in scala.

def tryToClaimPosition(player: Int, horizontal: Int , vertical: Int , list: List[(Int, Int)]): Unit = {
if (vertical == gridsize - 1) {
  println(list);
}
if (horizontal < gridsize - 1) {
  if (gameBoard(horizontal)(vertical) == player) {
    val tuple = (horizontal,vertical)
    val list2 = list :: tuple
    tryToClaimPosition(player, horizontal + 1, vertical, list2)
  else {
    tryToClaimPosition(player, horizontal + 1, vertical, list)
  }
}

As you see in the snippet above I have a List of tuples and I have a tuple, but I cannot add it.

Upvotes: 1

Views: 156

Answers (2)

Andronicus
Andronicus

Reputation: 26076

I'd use immutable list instead, that would be an accumulator. This would be in a more functional way. The function would have no side effect and would return a resulting List:

def tryToClaimPosition(player: Int, horizontal: Int , vertical: Int , list: List[(Int, Int)]): List[(Int, Int)] = {
  if (vertical == gridsize - 1) {
    list.reverse
  }
  if (horizontal < gridsize - 1) {
    if (gameBoard(horizontal)(vertical) == player) {
      val tuple = (horizontal, vertical)
      tryToClaimPosition(player,horizontal + 1, vertical, tuple::list)
    else {
      tryToClaimPosition(player,horizontal + 1, vertical, list)
    }
  } else Nil
}

Notice, that I have prepended the tuple to the List, because it takes constant time (appending is proportional to the size of the List). That's why I'm returning list.reverse, so that the original ordering is maintained.

Also I asked about the case when horizontal > gridsize - 1. Your program does nothing, so I assume, nothing should be returned, hence Nil in else clause. It is needed, so that there is always a value returned from the function.

Upvotes: 2

jwvh
jwvh

Reputation: 51271

Your code has many glaring logic and syntax errors. Most pertinent to your question is that fact that list :: tuple won't compile because the right side of the :: method must be a List.

Use :: to prepend, not append, to a List.

Upvotes: 2

Related Questions