Kevin Meredith
Kevin Meredith

Reputation: 41919

Scala Using Case Statements with +

Still working on hw1 of the Coursera Scala course, I'm having trouble with case statements and tuples.

object Pascal {
    def main(args: List[String]) = {
        require((args length) == 2, "args length must equal 2")
          println("calling pascal on " + (args head) + " and " + (args last))
          pascal((args head) toInt, (args last) toInt)
    }
    def pascal(c: Int, r: Int): Int = {
        require(((r >= 0) && (c >= 0))
            && (c > r + 1), "r and c must be >= 0 and c must be <= r + 1")
        (c, r) match {
            case (_, 0) => 1
            case (0, _) => 1
            case (1 + r, _) => 1 // error: value not found "+"
            case (_, _) => pascal(r-1,c-1) + pascal(r-1,c-1)
        }
    }
}

Please tell me how to code this in Scala:

case (1 + r, _) => 1

Upvotes: 2

Views: 1850

Answers (2)

Rex Kerr
Rex Kerr

Reputation: 167901

You can also

val R = r+1
(c, r) match {
  case (0, _) => 1
  case (R, _) => 1
  case (_, _) => pascal(r-1, c-1) + pascal(r-1,c)
}

(Note that the recursion you have is wrong--you add the same entry twice!--and that case (_, 0) is unnecessary since if r is 0, either c is 0 (which is caught by its case), or c is r+1, which is caught by that case.)

Upvotes: 3

jcern
jcern

Reputation: 7848

I believe you are looking for something like this:

case (v, _) if(v == r + 1) => 1

which will match any value of c (except for c == 0 which was matched previously) and then apply a test to check if v is equal to r + 1

Upvotes: 4

Related Questions