我有一個示例文件(選項卡分隔),我必須使用線性遞歸來搜索給定狀態的樹列表。斯卡拉列表搜索遞歸
輸入文件:
Quercus acerifolia mapleleaf oak MN
Quercus _acutidens CA
Quercus acutissima sawtooth oak AL,GA,LA,MD,MS,NC,PA,VA
Quercus agrifolia California live oak CA
Quercus alba white oak AL,AR,CT,DC,DE,FL,GA,IA,IL,IN,KS,KY,LA
Quercus ajdfensis Ajo Mountain scrub oak ,MN
First Column - Tree Name(Genus Species)
Second Column - Common Tree name
Third Column - State Name
代碼使用遞歸:
//declaring package
package HW10
//declaring object
object TreesStub {
//importing Source package for files import
import scala.io.Source
//assigning the file path to filename variable
val fileName = "trees.tsv" //tab separated
//defining Main function
def main(args: Array[String]): Unit = {
//reading source file from a file which is tabe separated
val treeList: List[String] = Source.fromFile(fileName).getLines.toList
//Creating mutable list to append element which found a match
var stateList = collection.mutable.ListBuffer[String]:()
//Checking the list if empty then print empty list else call the function
if(treeList.isEmpty) println("Empty List")
else searchTreesRecursively(state,treeList) //calling recurive func
//Calling recursive function search trees using "state" name and each line of //file(as second parameter)
def searchTreesRecursively(state: String, trees: List[String]): Unit = {
//matching the trees list
trees match {
case Nil => println(stateList) //If empty print the entire list
//taking each line and splitting the lines using and matching with the state //given
case x => x.map(x => (x.split("\t", -1))).filter(_.length > 2).map(x1=> if(x1(2).contains(state)) stateList+= x(0)
//calling function recursively for the rest of the elements of the list
else searchTreesRecursively(state,x1->next)}//next //element of list
}
}
}
我在這裏想呼籲在case語句列表中的 「X1」 的每一個元素的遞歸函數。我不知道如何通過遞歸調用列表的第二個元素,我使用了「searchTreesRecursively(state,x1-> next)}」但是我得到的錯誤是「Type Mismatch」。
I know we can use x::xs for iterating the list, but i am not sure how i can use it to fit in this logic. Please let me know.
'X1-> next'是一個lambda,而不是一個'清單[字符串]'。我想你需要使用'x1.next'。或者甚至可能是'trees.tail'? 'x1'在哪裏定義? – marstran
我做了x1.next,但沒有工作。 x1是「map」函數中的項目。下面是代碼行: - map(x1 => {if(x1(2).contains(state))stateList + = x(0)else searchTreesRecursively(state,x1.next )})} – Issaq
'x1-> next'不是lambda它的元組,但是下一個沒有值,我假設你想用.tail獲得列表的尾部,但是爲什麼你要在整個列表中進行映射時間? –