Ich habe eine Beispieldatei (Registerkarte getrennt), ich muss lineare Rekursion verwenden, um die Baumliste für einen bestimmten Zustand zu suchen.Scalaliste Suche rekursiv
Eingabedatei:
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
-Code mit Rekursion:
//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
}
}
}
Hier bin ich versucht, die rekursive Funktion für jedes Element der Liste "x1" in case-Anweisung zu nennen. Ich bin nicht sicher, wie man das zweite Element der Liste durch recursion aufruft, das ich "searchTreesRecursively (Zustand, x1-> nächstes)"} benutzte, aber ich erhalte Störung als "Art 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' ist ein Lambda, kein' Liste [Zeichenfolge] '. Sie müssen 'x1.next' verwenden, denke ich. Oder vielleicht sogar 'trees.tail'? Wo ist 'x1' definiert? – marstran
Ich habe die x1.next auch, aber hat nicht funktioniert. x1 ist das Element in der Funktion "map". Hier ist die Codezeile: - map (x1 => {if (x1 (2) .enthält (state)) stateList + = x (0) else searchTreesRecursively (state, x1.next)})} – Issaq
'x1-> next' ist kein Lambda, es ist ein Tupel, aber es gibt keinen Wert für die nächste, ich nehme an, Sie möchten den Schwanz der Liste mit .tail bekommen, aber warum mappen Sie über die gesamte Liste Zeit? –