Scala:列表匹配有/没有替换

问题描述 投票:0回答:1

以下是可以正常工作的函数定义:

case class Type(unique:String, tech:String)
case class TVal(tech:String, value:String)

  def f1(techName:String, variables: List[TVal]):String =
    variables.filter(variable =>
      techName == variable.tech)
      .map(variable => variable.value) match {
      case Nil => "empty list"
      case head::Nil => head
      case head::tail => "more than one"
    }

  def f2(defList:List[Type],
         variables: List[TVal]):List[Tuple2[String,String]] =
    defList.map(t => {
      t.unique -> f1(t.tech, variables)
    })

  def comp(defList:List[Type],
           variables: List[TVal]):Map[String,String] =
    Map(f2(defList, variables): _*)

现在我尝试用它的主体替换每个函数调用:

  def compSubstitution(defList:List[Type],
                       variables: List[TVal]):Map[String,String] =
    Map(defList.map(t => {
      t.unique -> variables.filter(variable =>
        t.tech == variable.tech)
        .map(variable => variable.value) match {
        case Nil => "empty list"
        case head::Nil => head
        case head::tail => "more than one"
      }
    }): _*)

现在我收到编译错误:

Error:(33, 14) pattern type is incompatible with expected type;
 found   : scala.collection.immutable.Nil.type
 required: (String, List[String])
        case Nil => "empty list"
Error:(33, 14) type mismatch;
 found   : scala.collection.immutable.Nil.type
 required: (String, List[String])
        case Nil => "empty list"
Error:(34, 18) constructor cannot be instantiated to expected type;
 found   : scala.collection.immutable.::[B]
 required: (String, List[String])
        case head::Nil => head
Error:(35, 18) constructor cannot be instantiated to expected type;
 found   : scala.collection.immutable.::[B]
 required: (String, List[String])
        case head::tail => "more than one"
Error:(29, 20) type mismatch;
 found   : List[String]
 required: Seq[(String, String)]
    Map(defList.map(t => {

它怎么可能?你能描述一下吗?

scala pattern-matching substitution
1个回答
3
投票

您正在将类型(String - > List [String])与Nil匹配,并且您只想匹配List吗?

所以我认为你只缺少括号:

def compSubstitution(defList:List[Type], variables: List[TVal]):Map[String,String] =
   Map(defList.map(t => {
t.unique ->(
  variables.filter(variable => t.tech == variable.tech)
  .map(variable => variable.value) match {
  case Nil => "empty list"
  case head::Nil => head
  case head::tail => "more than one"
})
   }): _*)
© www.soinside.com 2019 - 2024. All rights reserved.