Scala列表以递归方式搜索

时间:2017-04-24 13:34:09

标签: scala

我有一个示例文件(制表符分隔),我必须使用线性递归来搜索给定状态的树列表。

输入文件:

    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

        }
      }

    }

这里我试图为列表中的每个元素调用递归函数" x1"在案件陈述中。我不知道如何通过我使用的递归来调用列表的第二个元素" searchTreesRecursively(state,x1-> next)}"但我得到错误"输入错误"。

    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.

1 个答案:

答案 0 :(得分:0)

问题在于此模式匹配中的模式,

所以...... Scala中的List可以被认为是,

list = elem1 :: elem2 :: elem3 :: Nil

,或者

list = elem1 :: (elem2 :: (elem3 :: (Nil)))

,或者

list = elem1 :: tail1

其中,

tail1 = (elem2 :: (elem3 :: (Nil)))

因此,如果我们想要递归地对此列表的元素执行abcdef

def abcdef(list: List[String]): Unit = {
  case Nil => println("nil")
  case head :: tail => {
    println(head)
    abcdef(tail)
  }
}