Scala自定义List头部替换head函数的实现问题咨询
head Method Implementation Hey there! Let's walk through fixing your code to get that head method working as intended—replacing the first element of your custom List. Here's what was off in your original code, plus the corrected version:
Issues in Your Original Code
Generic Parameter Shadowing:
Your traitList[+A]defines ahead[A](x: A)method, where the method-levelAshadows the trait'sA. This causes type mismatches because the method'sAis a completely separate type parameter, not the one tied to your List.Incomplete
ConsClass:
TheConscase class wasn't finished—it was missingextends List[A]and didn't implement theheadmethod required by the trait.Missing
ListCompanion Object:
While not strictly an error, you need a companion object with anapplymethod to easily create List instances likeList(1,2,3,4).
Corrected Full Code
sealed trait List[+A] { def tail(): List[A] // Use B >: A to support covariance (allow replacing with a parent type of A) def head[B >: A](x: B): List[B] } object Nil extends List[Nothing] { def tail(): List[Nothing] = throw new NoSuchElementException("Nil has no 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](x: B): List[B] = Cons(x, xs) } // Companion object for easy List creation object List { def apply[A](as: A*): List[A] = if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*)) }
How It Works
- Covariance Handling: The
[B >: A]in theheadmethod lets you replace the head element with a value of a parent type ofA, which aligns with your List's covariant+Adeclaration. Cons'sheadImplementation: When you callhead(x)on aCons, it returns a newConswithxas the new head and the original tail—exactly what you want for replacing the first element.Nil'sheadImplementation: If you callhead(x)on an emptyNil, it returns a single-element list withx(since there's no existing head to replace).
Testing It Out
Run this in your Scala REPL:
List(1,2,3,4).head(4) // Returns Cons(4, Cons(2, Cons(3, Cons(4, Nil)))) // Which behaves exactly like your desired List(4,2,3,4)
内容的提问来源于stack exchange,提问作者Giorgio

