-3

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!

3 Answers3

4

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.

Andrei T.
  • 2,455
  • 1
  • 13
  • 28
1

the ? : operator doesn't exist in scala

Frederic A.
  • 3,504
  • 10
  • 17
1

Scala does not use the ternary operator, http://alvinalexander.com/scala/scala-ternary-operator-syntax

Tanjin
  • 2,442
  • 1
  • 13
  • 20