我是斯卡拉新手。斯卡拉列表索引
例如,我有一個像
val s = List(5, 11, 15, 7)
一個列表,我需要一個lambda函數來創建超過10我無法用語言元素的索引的一個新的列表Scala庫或函數。只有標準的Scala機會。
我該如何計算這些元素的指數?謝謝!
我是斯卡拉新手。斯卡拉列表索引
例如,我有一個像
val s = List(5, 11, 15, 7)
一個列表,我需要一個lambda函數來創建超過10我無法用語言元素的索引的一個新的列表Scala庫或函數。只有標準的Scala機會。
我該如何計算這些元素的指數?謝謝!
試試這個代碼:
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)
嗯...有可能的方式來解決這個問題。現在
首先讓我們看看更廣泛地「勢在必行」般的解決方案與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
}
這很有趣,你稱爲*命名方法* a * lambda * :) –
是的......這很有趣。 –
您的功課...? –
@groenhen almost) – Alex
如何幫助其他人提供答案,以明確自己分配的或實際的課程作業? –