【问题标题】:How to create a function with zipWithIndex that returns an Int from a List[Int] in scala如何使用 zipWithIndex 创建一个函数,该函数从 scala 中的 List[Int] 返回一个 Int
【发布时间】:2020-06-19 20:30:29
【问题描述】:

我正在尝试使用 zipWithIndex 来索引我的 List 中的第一个负值,方法是创建一个采用 List[Int] 并返回一个Int 或选项[Int] 供我使用。首先,我使用 zipWithIndex 创建了列表和函数,但我不断收到类型不匹配错误:

val list = List(-2,-1,2,3,4)

def getNegativeIndex(xs: List[Int]): Int = {
  
    for ((x, count) <- xs.zipWithIndex if x < 0) yield(count)
}

这是我不断收到的错误:

type mismatch;
 found   : List[Int] => Int
 required: Int

我的目标是索引列表的第一个负值“list” 即我的结果应该是 getNegativeIndex(list) == 0 使用我提供的列表,因为第一个元素 -2 位于索引 0

请问,我需要在上面的函数中添加或删除什么来实现我的目标

【问题讨论】:

  • zipWithIndex 不接受参数。因此,当您执行list.zipWithIndex(getNegativeIndex(_)) 时,它将期望一个整数,因为它等效于list.zipWithIndex.apply(getNegativeIndex(_))。但也许为了澄清,你能提供所需的输出吗?
  • 谢谢@Yann。从我提供的列表中,我想要的输出应该是 (-2, 0),其中 -2 是列表中的第一个负元素,0 是索引。
  • 对不起,它应该使用提供的列表返回索引 0

标签: user-defined-functions scala-collections


【解决方案1】:

为了让 getNegativeIndex(list) 返回单个整数和您想要的值,您只需返回您的 for-comprehension 生成的列表中的 headOption

目前的for-comprehension相当于 xs.zipWithIndex.filter(_._1 &lt; 0).map(_._2)。所以你可以这样做

xs.zipWithIndex.filter(_._1 < 0).map(_._2).headOption

或者像这样在你的理解中添加headOption

(
  for ((x, count) <- xs.zipWithIndex if x < 0) yield(count)
).headOption

结果将是相同的,即函数返回列表中负数的第一个索引或None,如果所有都是非负数。您可以改为使用.head 直接获取整数,但请注意,如果列表不包含任何负数或为空,它将引发异常。

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 2014-06-28
    • 2021-03-29
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多