4

I keep getting this error when writing a simple recursive function in Scala. What am I missing?

scala> def count(n1:Int, n1:Int) : List[Int] = (n1 < n2) ? List() : List(n1, count((n1 - 1), n2))
<console>:1: error: ';' expected but '(' found.
   def count(n1:Int, n1:Int) : List[Int] = (n1 < n2) ? List() : List(n1, count((n1 - 1), n2))
Anas
  • 73
  • 1
  • 2
  • 6
  • 2
    you probably want your else clause to be `n1 :: count((n1 - 1), n2)` –  Jan 17 '13 at 07:57
  • See also: http://stackoverflow.com/questions/8238184/why-not-provide-an-operator-in-scala – Jesper Jan 17 '13 at 08:20

2 Answers2

6

In Scala the ternary operator is if. So, ? and : can be replaced with the usual if and else keywords.

Also, where is n2 defined? I'll guess in countlike this def count(n1:Int, n2:Int) : List[Int] = ...

Brian
  • 20,195
  • 6
  • 34
  • 55
  • The n2 is just a typo. I changed the operator to `if` and now I'm getting another error. ` :1: error: illegal start of simple expression def count (n1:Int, n2:Int) : List[Int] = def count (n1:Int, n2:Int) : List[Int] = if (n1 < n2) List() else n1 :: count(n1 - 1, n2) ^ ` – Anas Jan 18 '13 at 03:37
  • The code in your comment has `def count (n1:Int, n2:Int) : List[Int] =` defined twice. – Brian Jan 18 '13 at 07:11
1

This works!

def count(n1:Int, n2:Int) : List[Int] = if (n1 < n2) List() else n1 :: count((n1 - 1), n2))

change count(n1:Int, n1:Int) to count(n1:Int,n2) The rest is adding an if else clause instead of the ternary oprator.

A similar code for doing this would be def count(n1:Int, n2:Int) = (n1 to n2).reverse

korefn
  • 955
  • 6
  • 17