Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala中使用尾部递归查找列表中的整数_Scala - Fatal编程技术网

在Scala中使用尾部递归查找列表中的整数

在Scala中使用尾部递归查找列表中的整数,scala,Scala,我尝试在Scala中使用尾部递归在列表中查找一个整数, 示例列表:(1,2,3,4) 我想找到一个值:3 我希望它返回一个布尔值,无论它是否在列表中。 谢谢你的帮助 def findInList(list: List[Int], intToFind: Int): Boolean = { findInList(list, 0, intToFind) } def findInList(list: List[Int], index: Int, intToFind: Int): Boolean =

我尝试在Scala中使用尾部递归在列表中查找一个整数, 示例列表:(1,2,3,4) 我想找到一个值:3 我希望它返回一个布尔值,无论它是否在列表中。 谢谢你的帮助

def findInList(list: List[Int], intToFind: Int): Boolean = {
  findInList(list, 0, intToFind)
}

def findInList(list: List[Int], index: Int, intToFind: Int): Boolean = {
  if(index >= list.length)
    false
  else if(list(index) == inToFind)
    true
  else
    findInList(list, index + 1, intToFind)
}

只需调用
def findInList(list:list[Int],intToFind:Int)
就可以得到结果。

到目前为止,您做了哪些尝试?什么不起作用?为什么要使用递归只要使用
contains
,它将返回
true/false
。为什么有人否决了它?问题是,Scala中的
List
LinkedList
,因此
Scala中
List
上的
List(index)
O(n)
。这意味着您确实避免了多次
list(index)
调用,除非明确要求。