2017-02-18 130 views
-1

我是斯卡拉新手。斯卡拉列表索引

例如,我有一個像

val s = List(5, 11, 15, 7)

一個列表,我需要一個lambda函數來創建超過10我無法用語言元素的索引的一個新的列表Scala庫或函數。只有標準的Scala機會。

我該如何計算這些元素的指數?謝謝!

+3

您的功課...? –

+0

@groenhen almost) – Alex

+1

如何幫助其他人提供答案,以明確自己分配的或實際的課程作業? –

回答

0

試試這個代碼:

val lambda = (list: List[Int]) => { 

    def filterList(l : List[Int], condition : Int, index: Int, acc: List[(Int, Int)]) : List[(Int, Int)] = l match { 
    case List() => acc 
    case h::tail => 
     if (h > condition) filterList(tail, condition, index + 1, (index, h) :: acc) 
     else filterList(tail, condition, index + 1, acc) 
    } 

    filterList(list, 10, 0, List()) 
} 

val r = lambda(s) 
+0

謝謝,但我不能使用內置的函數(如zipWithIndex) – Alex

+0

剛剛更新,我會假設你需要用一些函數替換條件,所以這將是更高階的函數 – Pavel

+0

我會做一個假設什麼「lambdas 「並不那麼相關,因爲你可以重複使用上面的代碼作爲lambdas的模板。 – Pavel

0

嗯...有可能的方式來解決這個問題。現在

首先讓我們看看更廣泛地「勢在必行」般的解決方案與var

val lambda = (list: List[Int]) => { 
    var indexList = List.empty[Int] 
    var i = 0 
    for (elem <- list) { 
    if (elem > 10) indexList = i +: indexList 
    i = i + 1 
    } 
    indexList.reverse 
} 

...大家可以看看多一點「功能類」遞歸方法,

val lambda = (list: List[Int]) => { 
    def _inner(list: List[Int], index: Int, indexList: List[Int]) = { 
    list match { 
     case Nil => indexList 
     case elem :: tail => { 
     if (elem > 10) _inner(tail, index + 1, index +: indexList) 
     else _inner(tail, index + 1, indexList) 
     } 
    } 
    } 

    _inner(list, 0, List.empty[Int]).reverse 
} 
+0

這很有趣,你稱爲*命名方法* a * lambda * :) –

+0

是的......這很有趣。 –