我在编写一个名为 head 的函数时遇到了问题,它基本上将头元素替换为另一个用于调用它的List:
List(1,2,3,4).head(4) // List(4,2,3,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(2,Cons(3,Cons(4,Nil)))).tail()
List(1,2,3,4,5,6,7).tail()
List(1,2,3,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)
你能解释一下原因吗?
问候。
答案 0 :(得分:5)
Your problem is that your head
method is taking another type A
, therefore inside that scope the compiler takes those A
s as different, i.e., the A
defined in the trait is shadowed by the A
in head[A]
.
Also, your head
method is taking a covariant element of type A
in a contravariant position, so you can't define head
as such.
What you can do is defining your head
as:
def head[B >: A](x: B): List[B]
Hence, you get:
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: _*))
}
}
}
Testing this on the 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)
答案 1 :(得分:1)
您的方法头不需要类型参数,因为您已经在类定义中定义了一个类型参数,这正是您希望头部接收的类型(如果您希望头部创建相同类型的原始列表) )。
你得到的错误是因为A是方法头的上下文中的两种不同类型(方法中的一种,另一种来自类)。
头部的定义应该是:
def head(x:A):List[A]