From working on the first problem of the 99 Scala Puzzles I defined my own version of last like so:
def last[A](xs: List[A]): A = xs match {
case x :: Nil => x
case x :: xs => last(xs)
}
My question is: Why is it necessary for last to be directly followed by the type variable, as in last[A]? Why couldn't the compiler just do the right thing if I wrote the function like so:
def last(xs: List[A]): A
.....
(leaving the [A] off the end of last[A]?)
And if the compiler is capable of figuring it out, then what is the rationale for designing the language this way?
AinList[A]doesn't refer to an actual type calledA?Ain scope, conceivably could introduce an implicit declaration at the most local scope that makes sense.lastis a method, not a function. Functions are declared like this:val length: List[_] => Int = xs => xs match { case Nil => 0; case x :: xs => 1 + length(xs) }Note: I don't think you can writelastas a function since functions can't be polymorphic AFAIK. The closest you can get isval last: List[Any] => Any = xs => xs match { case x :: Nil => x; case x :: xs => last(xs) }which is practically useless because you lose any information about the element type.