用Scala中的模式匹配替换._1和.head

问题描述 投票:0回答:2
  def checkPeq[A,B](list1: List[(A, List[B])])( P: (A,B) => Boolean): List[Boolean] = {
    def helper[A,B](list2: List[(A, List[B])], list3: List[B], acc1: Boolean, acc2: List[Boolean])(leq:(A,B) => Boolean): List[Boolean] = {
      list2 match {
        case h1::t1 => {
              list3 match {
                case Nil if t1!=Nil => helper(t1, t1.head._2, true, acc1::acc2)(leq)
                case Nil => (acc1::acc2).reverse
                case h2::t2 if(leq(h1._1, h2)) => helper(list2, t2, acc1, acc2)(leq)
                case h2::t2 => helper(list2, t2, false, acc2)(leq)
              }
        }
      }
    }
    helper(list1, list1.head._2, true, List())(P)
  }
  val list1 = List((1,List(1,2,3)), (2, List(2,3)), (3, List(3,2)), (4, List(4,5,6,3)))
  println(checkPeq(list1)(_<=_))

我有一个尾部递归函数,它返回List [Boolean],在这种情况下为List(true,true,false,false)。它正在工作,但是问题是我需要在没有._或.head且最好没有索引的情况下执行此操作(bcz我可以在此函数中轻松地将.head替换为(0))。我需要通过模式匹配来做到这一点,但我不知道如何开始。我也从老师那里得到了一个提示,它应该很快。非常感谢您提供有关如何解决此问题的提示。

scala pattern-matching
2个回答
0
投票

一种解决方案是简单地同时对外部A列表和内部B列表进行模式匹配,即作为单个模式的一部分。

def checkPeq[A,B](in: List[(A,List[B])])(pred: (A,B) => Boolean): List[Boolean] = {
  @annotation.tailrec
  def loop(aLst :List[(A,List[B])], acc :List[Boolean]) :List[Boolean] =
    aLst match {
      case Nil               => acc.reverse          //A list done
      case (_,Nil)    :: aTl => loop(aTl, true::acc) //B list done
      case (a,b::bTl) :: aTl =>                      //test a and b
        if (pred(a,b)) loop((a,bTl) :: aTl, acc)
        else           loop(aTl, false::acc)
    }
  loop(in, List.empty[Boolean])
}

0
投票

这里缺少一些片段,应该可以帮助您解决其余问题:

与列表匹配的模式

val l = List(2,3)

l match {
  case Nil          => "the list is empty"
  case head :: Nil  => "the least has one element"
  case head :: tail => "thie list has a head element and a tail of at least one element"
}

与元组匹配的模式

val t = (75, "picard")

t match {
  case (age, name) => s"$name is $age years old"
}

与元组列表匹配的模式

val lt = List((75, "picard"))

lt match {
  case Nil                 => "the list is empty"
  case (name, age) :: Nil  => "the list has one tuple"
  case (name, age) :: tail => "the list has head tuple and a tail of at least another tuple"
}

与元组列表的元组匹配的模式

val lt = List((75, "picard"))
val ct = List((150, "Data"))

(lt, ct) match {
  case (Nil, Nil)                 => "tuple of two empty lists"
  case ((name, age) :: Nil, Nil)  => "tuple of a list with one tuple and another empty list"
  case (Nil, (name, age) :: Nil)  => "tuple of an empty list and another list with one tuple"
  case ((name, age) :: tail, Nil) => "tuple of list with head tuple and a tail of at least another tuple, and another empty list"
  case _ => "and so on"
}

请注意如何组成图案。

© www.soinside.com 2019 - 2024. All rights reserved.