Reputation: 11
I'm dealing with a simple Scala program in which I defined two auxiliary functions:
def getInt(number: String): Int ={
if(number=="NULL") 0
else number.toInt
}
def getFloat(number: String): Float ={
if(number=="NULL") 0
else number.toFloat
}
And a third recursive function that call them:
def foldr_rating_state(l: List[(String, String, String)], sum_sat:Int, n_sat:Int, sum_ret:Float, n_ret:Int) :Float = {
match l{
case Nil => ((sum_sat/n_sat)/1600)*(1-(sum_ret/n_ret)).toFloat
case x::xs => {
foldr_rating_state(xs.asInstanceOf[List[(String, String, String)]],
sum_sat+getInt(x(1)),
n_sat+(if (getInt(x(1))==0) 0 else getInt(x(1))),
sum_ret+getFloat(x(2)),
n_ret+(if (getFloat(x(2))==0.toFloat) 0 else getFloat(x(2))).toInt
)
0.toFloat
}
case _ => 0.toFloat
}
}
But the compiler tells me that:
before "match l" a { is expected
Illegal start of statement at the same point
And IntelliJ says
Expression of type (String, String, String) doesn't conform to expected type Float
If I remove ".asInstanceOf[List[(String, String, String)]]" I get
Type mismatch, Expected List[(String, String, String)], Actual: List[Any]
Do you have any idea about the cause of these problems?
Thanks in advance!
Upvotes: 1
Views: 1923
Reputation: 7152
You are accessing the fields of your tuples in a wrong way and the l
blongs to the left of match
. Try this
def foldr_rating_state(l: List[(String, String, String)], sum_sat:Int, n_sat:Int, sum_ret:Float, n_ret:Int) :Float = {
l match {
case Nil =>
((sum_sat/n_sat)/1600)*(1-(sum_ret/n_ret)).toFloat
case x :: xs => {
foldr_rating_state(
xs,
sum_sat+getInt(x._1),
n_sat+(if (getInt(x._1)==0) 0 else getInt(x._1)),
sum_ret+getFloat(x._2),
n_ret+(if (getFloat(x._2)==0.0f) 0 else getFloat(x._2).toInt
)
}
case _ => 0.0f
}
}
A word about getFloat(x._2)==0.0f
: Comparing floating point types with ==
may yield unexpected results due to a lack of precision.
Upvotes: 2
Reputation: 4017
1) Change match l
to l match
2) Change x(1)
to x._1
(x
is a tuple, no a list)
Upvotes: 4