Search code examples
scalafunctionliteralsidentifier

Identifier expected but integer literal found


I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0 
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found. f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b) ^ one error found.

Thank you!


Solution

  • The if construct in Scala is an expression. As the others already said, there's no ternary operator because there's no need for it - the if being already an expression.

    I rewrote your function to a tail-recursive version (to avoid StackOverflowErrors), let's see how it looks:

    @tailrec def numEqual(f1: Int => Int, f2: Int => Int)(a: Int, b: Int, res: Int = 0): Int =
      if (a > b) res
      else {
        val inc = if (f1(a) == f2(a)) 1 else 0
        numEqual(f1, f2)(a + 1, b, res + inc)
      }
    

    Notice how the result of the if expression is assigned to inc - here you would normally use the ternary operator. Anyway, I hope this helps you.