scala - 如何模式匹配scala列表的头部和尾部类型?

标签 scala pattern-matching

我要pattern matchlist 的不同部分在 scala关于 head 的类型和 tail :

class Solution07 extends FlatSpec with ShouldMatchers {
  "plain recursive flatten" should "flatten a list" in {
    val list1 = List(List(1, 1), 2, List(3, List(5, 8)))
    val list1Flattened = List(1, 1, 2, 3, 5, 8)

    flattenRecur(list1) should be (list1Flattened)
  }

  def flattenRecur(ls: List[Any]): List[Int] = ls match {
    case (head: Int) :: (tail: List[Any]) => head :: flattenRecur(tail)
    case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail)
    case (head: List[Any]) :: (tail: List[Any]) => flattenRecur(head) :: flattenRecur(tail) // non-variable type... on this line.
  }
}

我得到:

Error:(18, 17) non-variable type argument Int in type pattern List[Int] (the underlying of List[Int]) is unchecked since it is eliminated by erasure case (head: List[Int]) :: (tail: List[Any]) => head.head :: flattenRecur(head.tail :: tail) ^



我错过了什么?我怎么可能在 head 上进行模式匹配和 tail类型 名单?

最佳答案

我同意带有 HList 的 @Andreas 解决方案是解决问题的一个很好的例子,但我仍然不明白这有什么问题:

 def flatten(ls: List[_]): List[Int] = ls match {
    case Nil => Nil
    case (a: Int) :: tail => a :: flatten(tail)
    case (a: List[_]) :: tail => flatten(a) ::: flatten(tail)
    case _ :: tail => flatten(tail)
  }

然后:
println(flatten(List(List("one",9,8),3,"str",4,List(true,77,3.2)))) // List(9, 8, 3, 4, 77)

我在您的任务中没有看到类型删除有任何问题,因为您实际上不需要测试被删除的类型。在我的示例中,我有意跳过了所有已删除的类型 - 以显示这一点。类型删除不清除列表元素的类型信息,它只清除你拥有的列表泛型的类型信息Any_就我而言 - 所以你根本不需要那个。如果我没有遗漏一些东西,那么在您的示例中,类型根本不会被删除,因为您无论如何都有 Any几乎无处不在。

关于scala - 如何模式匹配scala列表的头部和尾部类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34115045/

相关文章:

scala - 异常查询,未找到展平

Python:Rabin-Karp算法散列

regex - 在 Bash 扩展模式中转义 @(..)

python-3.x - 模式识别和序列检测

scala - 如何使用 Ammonite Ops 更改到某个目录并在其中执行操作?

scala - "String with Int"是什么意思?

scala - distinct() 是否对数据集进行排序?

scala - ArrayBuffer 的大小

f# - 纯模式匹配

scala - scala 是否支持多个模式匹配的一个默认子句?