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

带有类型参数的Scala List

发布时间:2020-12-16 09:04:37 所属栏目:安全 来源:网络整理
导读:我在编写一个名为head的函数时遇到了问题,它基本上用另一个函数替换头元素,用于调用它的List: List(1,2,3,4).head(4) // List(4,4) 代码显然没用,我只是想和Scala一起玩.这是代码: sealed trait List[+A]{ def tail():List[A] def head[A](x:A):List[A]}ob
我在编写一个名为head的函数时遇到了问题,它基本上用另一个函数替换头元素,用于调用它的List:

List(1,2,3,4).head(4) // List(4,4)

代码显然没用,我只是想和Scala一起玩.这是代码:

sealed trait List[+A]{
  def tail():List[A]
  def head[A](x:A):List[A]
}

object Nil extends List[Nothing]{
  def tail() = throw new Exception("Nil couldn't has tail")
  def head[A](x:A): List[A] = List(x)
}

case class Cons[+A](x :A,xs: List[A]) extends List[A]{
  def tail():List[A] = xs
  def head[A](a:A): List[A] = Cons(a,xs)
}

object List{
  def apply[A](as:A*):List[A] = {
    if (as.isEmpty) Nil
    else Cons(as.head,apply(as.tail: _*))
  }
}

Cons(1,Cons(2,Nil)) == List(1,2)
Cons(1,Cons(3,Cons(4,Nil)))).tail()
List(1,4,5,6,7).tail()
List(1,4).head(4)

它没有编译,我有这个错误:

Error:(11,39) type mismatch;
found   : A$A318.this.List[A(in class Cons)]
required: A$A318.this.List[A(in method head)]
 def head[A](a:A): List[A] = Cons(a,xs)

你能解释一下原因吗?

问候.

解决方法

你的问题是你的head方法采用另一种类型A,因此在该范围内编译器将那些作为不同的,即,在trait中定义的A被头部[A]中的A遮蔽.

此外,你的头部方法是在逆变位置中采用A型的协变元素,因此你不能像这样定义头部.

您可以做的是将您的头部定义为:

def head[B >: A](x: B): List[B]

因此,你得到:

object S {
    sealed trait List[+A] {
        def tail(): List[A]
        def head[B >: A](x: B): List[B]
    }

    case object Nil extends List[Nothing] {
        def tail() = throw new Exception("Nil doesn't have a tail")
        def head[B >: Nothing](x: B): List[B] = Cons(x,Nil)
    }

    case class Cons[+A](x: A,xs: List[A]) extends List[A] {
      def tail(): List[A] = xs
      def head[B >: A](a: B): List[B] = Cons(a,xs)
    }

    object List {
      def apply[A](as: A*): List[A] = {
        if (as.isEmpty) Nil
        else Cons(as.head,apply(as.tail: _*))
      }
    }
}

在REPL上测试:

scala> :load test.scala
Loading test.scala...
defined object S

scala> import S._
import S._

scala> Nil.head(1)
res0: S.List[Int] = Cons(1,Nil)

scala> Cons(1,Nil).head(4)
res1: S.List[Int] = Cons(4,Nil)

(编辑:李大同)

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

    推荐文章
      热点阅读