error: type mismatch; found : (Int, Int) => Int required: Int
I'm new to scala and confused why this code is giving me this error.
def div(m: Int, n: Int, i: Int): Int = {
(m: Int, n: Int) =>
if ((m - n) <= 0)
return i
else
div((m-n), n, (i开发者_运维知识库+1))
}
Help appreciated.
It looks like you're returning a function rather than an Int
like you're declaring.
Is this what you're trying to do:
def div(m: Int, n: Int, i: Int): Int = if ((m - n) <= 0) return i else div((m-n), n, (i+1))
(x: A) => y: B
means an anonymous function of type A => B
, so the expression you have between the braces is a function (Int, Int) => Int
, and that's what gets returned.
You use a big number of superflous stuff, the return
- keyword, parenthesis, and the whole (m: Int, n:Int) => - part.
def div (m: Int, n: Int, count: Int): Int =
if ((m - n) <= 0) count else div (m - n, n, count + 1)
If you like to use a match, you could do it this way:
def div (m: Int, n: Int, count: Int = 1): Int = (m - n) match {
case (diff: Int) if (diff <= 0) => count
case _ => div (m - n, n, count + 1) }
(note the default-argument of count = 1).
m,n,i are a little bit too much short-named variables for my taste. Beneath count
, nominator, denominator
would fit.
However, the implentation returns
(0 to 2).map (x => div (14+x, 5, 1))
res61: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 3, 4)
where I would expect (2, 3, 3) - you're rounding in the opposite direction.
if ((m - n) < 0) i-1 else ...
would fix that - changing the comparator, and returning i-1 (count-1).
However, this is not testet for values including 0 and negative values.
精彩评论