匹配列表列表中的单个元素

Lar*_*ann 2 scala

如果我有一个列表List [Any]就像这样

val list = List(List(1,1),2,List(3,List(5,8)))

然后我如何编写区分的匹配语句

  1. 任何非列表类型的单个元素(即上面的2个)
  2. 作为列表的元素(即列表(1,1)列表(3,列表(5,8)从上面)

或者在伪scala中

list match {
  case x:"single non-list element" => // do something with single element x
  case y:"where y is a list"       => // do something with list y
}
Run Code Online (Sandbox Code Playgroud)

通常的head :: tails匹配不起作用,因为head可以是包含其他列表的Any类型.

ais*_*rya 5

list foreach { 
  _ match {
    case x:List[_] => // list
    case _ => // anything else
  }
}
Run Code Online (Sandbox Code Playgroud)

应该工作我猜


Mar*_*amy 5

val (lists, nonlists) = list partition {case (x :: xs) => true case _ => false}

lists: List[Any] = List(List(1, 1), List(3, List(5, 8)))
nonlists: List[Any] = List(2)
Run Code Online (Sandbox Code Playgroud)