【问题标题】:Scala Pattern Matching with tupleScala 模式匹配与元组
【发布时间】:2012-12-20 05:26:35
【问题描述】:

我正在处理 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

请指教。

谢谢。

【问题讨论】:

    标签: scala pattern-matching


    【解决方案1】:

    这是 scala 中的无效语法:您需要使用所谓的 guards 来检查布尔属性:

    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”

    【讨论】:

    • 不确定分配是否明确需要使用模式匹配,但是这段代码不是将 c 和 r (它们已经是单独的参数)打包成一个元组,只是为了在这种情况下再次解包它们?我会用一个简单的 if
    • 你最后一段代码错了:case r == 0 不会编译
    • 我该怎么做:case "where c == r"?
    • @Kevin try (c,r) match { case(`c`,`c`) =&gt; ... } -- 这指示模式匹配按值进行比较
    • @Kevin scala-lang.org/node/166 如果与此无关,请ask a different question
    猜你喜欢
    • 2019-04-20
    • 2014-08-27
    • 1970-01-01
    • 2021-02-15
    • 2021-06-15
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多