【问题标题】:Scala Pattern matching with tuple typesScala模式匹配元组类型
【发布时间】:2019-04-20 03:21:32
【问题描述】:

以下方法抛出错误,甚至没有调用它。

type Checklist = (Int,String,Boolean)
  def higherthan(a: Checklist,b:Checklist) : Boolean = (a._1,b._1) match {
    case a._1 >= b._1 => true
    case a._1 < b._1 => false
    case _ => false
}

错误如下:

Error:(3, 14) not found: value >=case a._1 >= b._1 => true

不可能从模式匹配中访问元组的元素吗?我想检查清单的第一个元素中哪个更大。抱歉有任何错误,英语不是我的第一语言,我是一年级学生。

【问题讨论】:

    标签: scala pattern-matching tuples


    【解决方案1】:

    有几种方法:

    def higherthan(a: Checklist, b: Checklist) : Boolean = (a , b) match {
      case (x, y) if x._1 >= y._1 => true
      case _ => false
    }
    
    def higherthan(a: Checklist, b: Checklist) : Boolean = (a , b) match {
      case ((x, _, _), (y, _, _)) if x >= y => true
      case _ => false
    }
    
    def higherthan(a: Checklist, b: Checklist) : Boolean = a._1 >= b._1
    

    希望其中之一有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 2013-03-17
      • 2014-08-27
      • 2014-03-05
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多