如何在 Scala 中消除 ++
How to get eliminate ++ in Scala
我在 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 ...
鉴于您只有一个元素作为 ++
的第二个参数,您可以自己实现它:
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
关键字。它对你没有任何作用
我在 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 ...
鉴于您只有一个元素作为 ++
的第二个参数,您可以自己实现它:
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
关键字。它对你没有任何作用