加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何模式匹配scala列表的head和tail类型?

发布时间:2020-12-16 18:51:54 所属栏目:安全 来源:网络整理
导读:我想在 scala中列表的不同段上模式匹配头部和尾部的类型: 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
我想在 scala中列表的不同段上模式匹配头部和尾部的类型:

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,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)
^

我错过了什么?我怎么可能在头部和尾部的列表类型上进行模式匹配?

解决方法

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

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),"str",4,List(true,77,3.2)))) // List(9,8,77)

我没有看到任务中的类型擦除有任何问题,因为您实际上不需要测试被擦除的类型.我故意在我的示例中跳过所有已删除的类型 – 以显示此信息.类型擦除不会清除列表元素的类型信息,它只清除您在任何情况下具有Any或_的列表通用类型信息 – 因此您根本不需要它.如果我没有错过某些东西,在你的例子中,类型根本没有被删除,因为你无论如何几乎无处不在.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读