1

Coursera クラスの最初の課題に取り組んでいます。

次のコードでは、コンパイル時のエラーが発生しています。

    object pascal {
        def main(c: Int, r: Int) = {
                pascal(c, r)
            }
            def pascal(c: Int, r: Int) = {
                (c, r) match {
                    case ((r < 0) || (c < 0)) => throw new Exception
                                                 ("r and c must be > 0")
                    case r == 0 => 1
                    case r == 1 => 1
                    case c == 0 => 1
                    case r == c => 1
                    case _ => pascal(r-1,c-1) + pascal(r-1,c-1)
            }
        }
     }

vagrant@precise64:/vagrant/Workspace/Scala/hw1$ scalac pascal.scala
pascal.scala:7: error: not found: value ||
                        case ((r < 0) || (c < 0)) => throw ...
                                      ^
pascal.scala:8: error: value == is not a case class constructor, nor 
does it have an unapply/unapplySeq method
                        case r == 0 => 1

お知らせ下さい。

ありがとう。

4

1 に答える 1

4

これはscalaでは無効な構文です。ブールプロパティをチェックするには、いわゆるガードを使用する必要があります。

def pascal(c: Int, r: Int) = {
   (c, r) match {
     case (c,r) if ((r < 0) || (c < 0)) => throw new Exception
                                                 ("r and c must be > 0")
     ...
}

ちなみに、このようなコードを書くのはもっと慣用的です:

def pascal(c: Int, r: Int) = {
   require((r >= 0) && (c >= 0), "r and c must be >= 0")
   (c, r) match {
     case (_, 1) => 1
     ...
}

そして、エラーメッセージを「rとcは>=0でなければならない」に変更する必要があります

于 2012-12-20T05:53:54.817 に答える