2017-02-18 83 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

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