質問

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