Reputation: 92
When trying to run a polymorphic function that abstracts over the type of the array, I get a type mismatch with the following error message:
Type mismatch: expected: (Int) => Boolean, actual: Int
val listIntegers = List(55, 50, 25, 23, 21, 16, 15)
def abstractSearchKey[A](a: List[A], p: A => Boolean): Int = {
def loop(n: Int): Int ={
if (n > a.length) -1
else if (p(a(n))) n
else loop(n+1)
}
loop(0)
}
abstractSearchKey[Int](listIntegers, 25)
I'm confused about this error message because this exercise is based on Chiusano's Functional Programming with Scala. In fact, on page 24, the authors state:
...the p function must accept a value of type A (since it's a function of type A => Boolean)
Any advice or feedback on this matter would be greatly appreciated!
Upvotes: 0
Views: 234
Reputation: 2392
The problem is that you are expecting a function (a predicate of type Int => Bool
)as the second argument of abstractSearchKey
, and you are pasing 25
which is an Int
.
Try passing a lambda function like x => x > 20
, for example, to be able to cut the loop using this predicate:
abstractSearchKey[Int](listIntegers, x => x > 20)
Edit: SergGr from the comments just pointed out that you might want this function: x => x == 25
instead, so it might be:
abstractSearchKey[Int](listIntegers, x => x == 25)
Upvotes: 3