我是斯卡拉新手。斯卡拉列表索引
例如,我有一个像
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
如何帮助其他人提供答案,以明确自己分配的或实际的课程作业? –