문제

I would like to implement a type-parametrized function as per excersize on page 72 of the book (implement forall using filter):

def forallA[B <: A](xs:List[A])(f:A => B) : List[B] = {
    xs.filter(x => true) match {
        case Nil => Nil
        case y :: ys => f(y) :: forallA(ys)(f)
    }
}

However, the compiler(2.9.1) complains about the type A being undefined. Clearly that should not be the case, since multiple examples in the same book use this syntax. The issue can be cured by changnig the function type parameter to [A, B <: A]. Am I doing something wrong, or is it again, a terrific change in Scala's syntax specification? If so, I am, frankfully, tired of bombing SO with such stupid questions on every second excersize. Could anyone recommend a book that clearly reflects the current order of things?

도움이 되었습니까?

해결책

You already gave the answer: If you want to bound the type parameter B with another type parameter A, you have to add this to the list of type parameters:

def forall[A, B <: A](...)(...) = ...

Else you are referring to something undefined. Maybe it helps if you think of type parameters like usual (method) parameters. How should something like the following compile:

def add(x: Int) = x + y

Here the parameter y is undefined, just like in your case A was undefined.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top