【问题标题】:Scala - Define a function with the following signature that searches for element n of a listScala - 定义具有以下签名的函数,用于搜索列表的元素 n
【发布时间】:2022-11-24 23:39:37
【问题描述】:

初始代码是:

def nth(list: List[Int], x: Int) = ??? 

我试试这个:

def nth(list: List[Int], n: Int): Option[Int] = 
  list match { 
    case h :: t if n > 0 => nth(t, n - 1) 
    case _ => list
  } 

但它不起作用

谢谢你帮我我试试以前的代码

【问题讨论】:

  • case _ => list 是 List[Int] 而不是 Option[Int],您也没有处理例如 2 元素列表将被要求提供第 4 个元素的情况。

标签: scala


【解决方案1】:

首先,由于返回类型是Option[Int],当列表少于 n 个(或 n-1 取决于 n 是基于零或基于 1 的)元素时,您需要返回 None,然后您需要返回 Some当您到达 nth 元素时。查看 Option 类型的 scaladoc。

例如,简单的递归解决方案可能如下所示(基于零的n):

def nth(list: List[Int], n: Int): Option[Int] =
  list match {
    case h :: t if n > 0  => nth(t, n - 1)
    case h :: t if n == 0 => Some(h)
    case _                => None
  }

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2011-05-11
    相关资源
    最近更新 更多