Return a list of user defined class type Scala

2019-08-03 18:27发布

问题:

I am trying to return a list of all the columns which are not full in below function. "isColumnFull" function will check if the list is full or not. GameState is a list of list. I am not sure where is the mistake. Could you please help?

type GameState = List[List[String]]

case class ColumnNum(index: Int)

val count = 0 //not sure this is needed
def allViableColumns(game: GameState): List[ColumnNum] = 
for((xs, count) <- game.zipWithIndex) yield {if(!isColumnFull(xs))List(count+1)} 

回答1:

If you want the indices of the columns:

type GameState = List[List[String]]
case class ColumnNum(index: Int)
def allViableColumns(game: GameState): List[ColumnNum] = 
  for((xs, i) <- game.zipWithIndex; if !isColumnFull(xs)) yield ColumnNum(i + 1)

If you want the columns, it's just:

def allViableColumns(game: GameState): List[List[String]] = 
  game filterNot isColumnFull

Should you decide to use the first version, consider changing (i + 1) to i: there are usually no good reasons for one-based indexing.