如何在Scala中消除++

时间:2016-02-02 15:46:08

标签: scala function operators

我在scala中有一段代码,但是我想从中删除++。代码运行正常,但我试图不使用++或任何内置函数或运算符(甚至不是:::)。

创建一个val是否更好,或者有更好的方法。

以下是该代码的示例。

def partitionAux[A](f: A => Boolean, lst: List[A], 
                       rslt: (List[A], List[A]) ):(List[A], List[A]) = {
  lst match {
    case Nil => return result
    case head :: rest => {
      if (f(head))
        return partitionHelper(f, rest, (result._1 ++ List[A](head), rslt._2))
      else ...

1 个答案:

答案 0 :(得分:1)

鉴于你只有一个元素作为++的第二个arg,你可以自己实现它:

 def concat[A](lst: List[A], a: A): List[A] =
    lst match {
      case Nil => a :: Nil
      case head :: tail => head :: concat(tail, a)
    }

println(concat(1 :: 2 :: 3 :: 4 :: Nil, 100)) // 1 :: 2 :: 3 :: 4 :: 100

另外,鉴于您提到partitionAux应该将列表拆分为两个,听起来您应该只有head :: result._1而不是result._1 ++ List[A](head),然后最后反转列表。自己编写反向函数很容易,比如:

@tailRec
def reverse[A](list: List[A], result: List[A] = Nil): List[A] = 
  list match {
    case Nil => result
    case head :: tail => reverse(tail, head :: result)
  }

P.S。而且您不需要在scala中放置return关键字。在你的情况下它没有做任何事情