Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala列表和拆分_Scala - Fatal编程技术网

Scala列表和拆分

Scala列表和拆分,scala,Scala,我有一个家庭作业,让我们使用一个列表,把它分成两部分,第一部分的元素不大于p,第二部分的元素大于p。所以它就像一个快速排序,除了我们不能使用任何排序。我真的需要一些关于如何做这件事的建议。我知道我在使用cases,但我不熟悉list类在scala中的工作方式。下面是我到目前为止所做的,但我不确定如何拆分这两个列表 使用 def split(p:Int, xs:List[Int]): List[Int] = { xs match { case Nil => (Nil, Nil)

我有一个家庭作业,让我们使用一个列表,把它分成两部分,第一部分的元素不大于p,第二部分的元素大于p。所以它就像一个快速排序,除了我们不能使用任何排序。我真的需要一些关于如何做这件事的建议。我知道我在使用cases,但我不熟悉list类在scala中的工作方式。下面是我到目前为止所做的,但我不确定如何拆分这两个列表

使用

 def split(p:Int, xs:List[Int]): List[Int] = {

 xs match {
   case Nil => (Nil, Nil)
   case head :: tail =>
 }

首先,您希望
split
返回一对列表,因此返回类型必须是
(List[Int],List[Int])
。然而,同时使用成对和列表通常意味着频繁分解返回值。你可能想有一个辅助功能来帮你做举重

例如,您的辅助函数可能会得到两个列表,最初为空,并构建内容,直到第一个列表为空。结果将是一对列表

在递归函数设计中,接下来要决定的是,“关键决定是什么?”在您的例子中,是“值不大于p”。这将导致以下代码:

def split(p:Int, xs: List[Int]): (List[Int], List[Int]) = {
  def splitAux(r: List[Int], ngt: List[Int], gt: List[Int]): (List[Int], List[Int]) =
    r match {
      case Nil => (ngt, gt)
      case head :: rest if head <= p =>
        splitAux(rest, head :: ngt, gt)
      case head :: rest if head > p =>
        splitAux(rest, ngt, head :: gt)
    }
  val (ngt, gt) = splitAux(xs, List(), List())
  (ngt.reverse, gt.reverse)
}
def拆分(p:Int,xs:List[Int]):(List[Int],List[Int])={
def splitAux(r:List[Int],ngt:List[Int],gt:List[Int]):(List[Int],List[Int])=
r匹配{
案例无=>(ngt,gt)
案例头部::如果头部静止
splitAux(静止,头部::ngt,gt)
案例头部::如果头部>p=>
splitAux(静止、下一代、头部::燃气轮机)
}
val(ngt,gt)=splitAux(xs,List(),List())
(下向倒车,燃气轮机倒车)
}
反转步骤并非绝对必要,但可能最不令人惊讶。类似地,第二个guard谓词显式表示所采用的路径

但是,有一种更简单的方法:使用内置功能

def split(p:Int, xs: List[Int]): (List[Int], List[Int]) = {
  (xs.filter(_ <= p), xs.filter(_ > p))
}
def拆分(p:Int,xs:List[Int]):(List[Int],List[Int])={
(xs.过滤器(p))
}

filter
仅提取符合条件的项目。此解决方案遍历列表两次,但由于您在上一个解决方案中有
反向
步骤,因此您仍在执行此操作。

您了解算法吗?如果您希望递归执行此操作,请在函数中引入signature splitHelper的helper函数(p:Int,input:list,greater:list,noGreater:list):(list,list). 显然,到处都是List[Int]。helper函数只能调用自身或返回结果。通过调用:splitHelper(p,xs,Nil,Nil)来实现您的主要功能。为什么要给出解决方案而不是帮助提出解决方案?如果允许内置功能,还有一种更简单的方法-使用
xs.partition(_