2016-02-02 24 views
-1

我在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 ... 
+1

1.什麼(partitionAux'應該做什麼;給出樣本輸入和輸出)? 2.爲什麼(你不想使用'++')? –

+0

這是我正在做的練習的一部分。 partitionAux是幫助者方法,它應該通過檢查其他函數是真還是假來將列表拆分爲2。 –

+0

樣本將是如果如果要拆分賠率和evens之間的列表:列表(0,1,3,4,6))==(列表(0,4,6),列表(1,3)) –

回答

1

假設你只有一個單一的元素作爲++第二阿根廷,你可以自己實現:

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.而且您不需要將return關鍵字放在scala中。它不會在你的情況下做任何事情

+0

好的。這有助於。謝謝。 –

+3

不僅你不需要把'return',你不應該。 –